From 20cf4fc5a15a303bd7ef2c5670feac768d39e946 Mon Sep 17 00:00:00 2001 From: "code@koerner-de.net" Date: Tue, 13 Mar 2012 19:02:45 +0000 Subject: [PATCH] uMod 2 branch --- .gitattributes | 79 + uMod2/.cproject | 58 + uMod2/.project | 71 + uMod2/README.txt | 58 + uMod2/uMod_DX9/makefile.gcc | 117 + uMod2/uMod_DX9/makefile.vc | 117 + uMod2/uMod_DX9/uMod_ArrayHandler.cpp | 106 + uMod2/uMod_DX9/uMod_ArrayHandler.h | 185 + uMod2/uMod_DX9/uMod_DX9_dll.cpp | 516 ++ uMod2/uMod_DX9/uMod_DX9_dll.h | 52 + .../uMod_DX9_dll_DIRECT_INJECTION.def | 5 + .../uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def | 6 + uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def | 13 + uMod2/uMod_DX9/uMod_Defines.h | 70 + uMod2/uMod_DX9/uMod_IDirect3D9.cpp | 156 + uMod2/uMod_DX9/uMod_IDirect3D9.h | 66 + uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp | 71 + uMod2/uMod_DX9/uMod_IDirect3D9Ex.h | 73 + uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp | 364 ++ uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h | 126 + uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp | 1224 +++++ uMod2/uMod_DX9/uMod_IDirect3DDevice9.h | 212 + uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp | 116 + uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h | 225 + uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp | 361 ++ uMod2/uMod_DX9/uMod_IDirect3DTexture9.h | 124 + .../uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp | 385 ++ uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h | 125 + uMod2/uMod_DX9/uMod_Main.h | 66 + uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp | 859 ++++ uMod2/uMod_DX9/uMod_TextureClient_DX9.h | 132 + uMod2/uMod_DX9/uMod_TextureFunction.cpp | 62 + uMod2/uMod_DX9/uMod_TextureFunction.h | 147 + uMod2/uMod_DXMain/uMod_TextureClient.cpp | 859 ++++ uMod2/uMod_DXMain/uMod_TextureClient.h | 163 + uMod2/uMod_DXMain/uMod_TextureServer.cpp | 828 ++++ uMod2/uMod_DXMain/uMod_TextureServer.h | 110 + uMod2/uMod_Error.h | 73 + uMod2/uMod_GUI/bin/README_Deutsch.txt | 116 + uMod2/uMod_GUI/bin/README_English.txt | 107 + .../Example_uMod_LanguagePack_English.txt | 152 + .../languages/uMod_LanguagePackU_Deutsch.txt | Bin 0 -> 6508 bytes .../languages/uMod_LanguagePackU_French.txt | Bin 0 -> 7008 bytes .../languages/uMod_LanguagePackU_Russian.txt | Bin 0 -> 6628 bytes uMod2/uMod_GUI/config.gcc | 149 + uMod2/uMod_GUI/config.vc | 149 + uMod2/uMod_GUI/makefile.gcc | 284 ++ uMod2/uMod_GUI/makefile.vc | 401 ++ uMod2/uMod_GUI/uMod.ico | Bin 0 -> 20462 bytes uMod2/uMod_GUI/uMod.rc | 1 + uMod2/uMod_GUI/uMod_AddTexture.cpp | 112 + uMod2/uMod_GUI/uMod_AddTexture.h | 54 + uMod2/uMod_GUI/uMod_Client.cpp | 93 + uMod2/uMod_GUI/uMod_Client.h | 45 + uMod2/uMod_GUI/uMod_DirectInjection.cpp | 519 ++ uMod2/uMod_GUI/uMod_DirectInjection.h | 27 + uMod2/uMod_GUI/uMod_Event.cpp | 23 + uMod2/uMod_GUI/uMod_Event.h | 70 + uMod2/uMod_GUI/uMod_File.cpp | 441 ++ uMod2/uMod_GUI/uMod_File.h | 62 + uMod2/uMod_GUI/uMod_GUI.cpp | 985 ++++ uMod2/uMod_GUI/uMod_GUI.h | 129 + uMod2/uMod_GUI/uMod_GameInfo.cpp | 333 ++ uMod2/uMod_GUI/uMod_GameInfo.h | 101 + uMod2/uMod_GUI/uMod_GamePage.cpp | 525 +++ uMod2/uMod_GUI/uMod_GamePage.h | 107 + uMod2/uMod_GUI/uMod_Language.cpp | 727 +++ uMod2/uMod_GUI/uMod_Language.h | 128 + uMod2/uMod_GUI/uMod_Main.h | 157 + uMod2/uMod_GUI/uMod_Sender.cpp | 424 ++ uMod2/uMod_GUI/uMod_Sender.h | 63 + uMod2/uMod_GUI/uMod_Server.cpp | 132 + uMod2/uMod_GUI/uMod_Server.h | 45 + uMod2/uMod_GUI/uMod_Settings.cpp | 157 + uMod2/uMod_GUI/uMod_Settings.h | 44 + uMod2/uMod_GUI/unzip.cpp | 4165 +++++++++++++++++ uMod2/uMod_GUI/unzip.h | 214 + uMod2/uMod_GUI/zip.cpp | 2830 +++++++++++ uMod2/uMod_GUI/zip.h | 203 + uMod2/uMod_GlobalDefines.h | 71 + 80 files changed, 22725 insertions(+) create mode 100644 uMod2/.cproject create mode 100644 uMod2/.project create mode 100644 uMod2/README.txt create mode 100644 uMod2/uMod_DX9/makefile.gcc create mode 100644 uMod2/uMod_DX9/makefile.vc create mode 100644 uMod2/uMod_DX9/uMod_ArrayHandler.cpp create mode 100644 uMod2/uMod_DX9/uMod_ArrayHandler.h create mode 100644 uMod2/uMod_DX9/uMod_DX9_dll.cpp create mode 100644 uMod2/uMod_DX9/uMod_DX9_dll.h create mode 100644 uMod2/uMod_DX9/uMod_DX9_dll_DIRECT_INJECTION.def create mode 100644 uMod2/uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def create mode 100644 uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def create mode 100644 uMod2/uMod_DX9/uMod_Defines.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3D9.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3D9.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3D9Ex.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DDevice9.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DTexture9.h create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp create mode 100644 uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h create mode 100644 uMod2/uMod_DX9/uMod_Main.h create mode 100644 uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp create mode 100644 uMod2/uMod_DX9/uMod_TextureClient_DX9.h create mode 100644 uMod2/uMod_DX9/uMod_TextureFunction.cpp create mode 100644 uMod2/uMod_DX9/uMod_TextureFunction.h create mode 100644 uMod2/uMod_DXMain/uMod_TextureClient.cpp create mode 100644 uMod2/uMod_DXMain/uMod_TextureClient.h create mode 100644 uMod2/uMod_DXMain/uMod_TextureServer.cpp create mode 100644 uMod2/uMod_DXMain/uMod_TextureServer.h create mode 100644 uMod2/uMod_Error.h create mode 100644 uMod2/uMod_GUI/bin/README_Deutsch.txt create mode 100644 uMod2/uMod_GUI/bin/README_English.txt create mode 100644 uMod2/uMod_GUI/bin/languages/Example_uMod_LanguagePack_English.txt create mode 100644 uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Deutsch.txt create mode 100644 uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_French.txt create mode 100644 uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Russian.txt create mode 100644 uMod2/uMod_GUI/config.gcc create mode 100644 uMod2/uMod_GUI/config.vc create mode 100644 uMod2/uMod_GUI/makefile.gcc create mode 100644 uMod2/uMod_GUI/makefile.vc create mode 100644 uMod2/uMod_GUI/uMod.ico create mode 100644 uMod2/uMod_GUI/uMod.rc create mode 100644 uMod2/uMod_GUI/uMod_AddTexture.cpp create mode 100644 uMod2/uMod_GUI/uMod_AddTexture.h create mode 100644 uMod2/uMod_GUI/uMod_Client.cpp create mode 100644 uMod2/uMod_GUI/uMod_Client.h create mode 100644 uMod2/uMod_GUI/uMod_DirectInjection.cpp create mode 100644 uMod2/uMod_GUI/uMod_DirectInjection.h create mode 100644 uMod2/uMod_GUI/uMod_Event.cpp create mode 100644 uMod2/uMod_GUI/uMod_Event.h create mode 100644 uMod2/uMod_GUI/uMod_File.cpp create mode 100644 uMod2/uMod_GUI/uMod_File.h create mode 100644 uMod2/uMod_GUI/uMod_GUI.cpp create mode 100644 uMod2/uMod_GUI/uMod_GUI.h create mode 100644 uMod2/uMod_GUI/uMod_GameInfo.cpp create mode 100644 uMod2/uMod_GUI/uMod_GameInfo.h create mode 100644 uMod2/uMod_GUI/uMod_GamePage.cpp create mode 100644 uMod2/uMod_GUI/uMod_GamePage.h create mode 100644 uMod2/uMod_GUI/uMod_Language.cpp create mode 100644 uMod2/uMod_GUI/uMod_Language.h create mode 100644 uMod2/uMod_GUI/uMod_Main.h create mode 100644 uMod2/uMod_GUI/uMod_Sender.cpp create mode 100644 uMod2/uMod_GUI/uMod_Sender.h create mode 100644 uMod2/uMod_GUI/uMod_Server.cpp create mode 100644 uMod2/uMod_GUI/uMod_Server.h create mode 100644 uMod2/uMod_GUI/uMod_Settings.cpp create mode 100644 uMod2/uMod_GUI/uMod_Settings.h create mode 100644 uMod2/uMod_GUI/unzip.cpp create mode 100644 uMod2/uMod_GUI/unzip.h create mode 100644 uMod2/uMod_GUI/zip.cpp create mode 100644 uMod2/uMod_GUI/zip.h create mode 100644 uMod2/uMod_GlobalDefines.h diff --git a/.gitattributes b/.gitattributes index c458c99..565cb88 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,84 @@ * text=auto !eol /README.txt -text +uMod2/.cproject -text +uMod2/.project -text +uMod2/README.txt -text +uMod2/uMod_DX9/makefile.gcc -text +uMod2/uMod_DX9/makefile.vc -text +uMod2/uMod_DX9/uMod_ArrayHandler.cpp -text +uMod2/uMod_DX9/uMod_ArrayHandler.h -text +uMod2/uMod_DX9/uMod_DX9_dll.cpp -text +uMod2/uMod_DX9/uMod_DX9_dll.h -text +uMod2/uMod_DX9/uMod_DX9_dll_DIRECT_INJECTION.def -text +uMod2/uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def -text +uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def -text +uMod2/uMod_DX9/uMod_Defines.h -text +uMod2/uMod_DX9/uMod_IDirect3D9.cpp -text +uMod2/uMod_DX9/uMod_IDirect3D9.h -text +uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp -text +uMod2/uMod_DX9/uMod_IDirect3D9Ex.h -text +uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp -text +uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h -text +uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp -text +uMod2/uMod_DX9/uMod_IDirect3DDevice9.h -text +uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp -text +uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h -text +uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp -text +uMod2/uMod_DX9/uMod_IDirect3DTexture9.h -text +uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp -text +uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h -text +uMod2/uMod_DX9/uMod_Main.h -text +uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp -text +uMod2/uMod_DX9/uMod_TextureClient_DX9.h -text +uMod2/uMod_DX9/uMod_TextureFunction.cpp -text +uMod2/uMod_DX9/uMod_TextureFunction.h -text +uMod2/uMod_DXMain/uMod_TextureClient.cpp -text +uMod2/uMod_DXMain/uMod_TextureClient.h -text +uMod2/uMod_DXMain/uMod_TextureServer.cpp -text +uMod2/uMod_DXMain/uMod_TextureServer.h -text +uMod2/uMod_Error.h -text +uMod2/uMod_GUI/bin/README_Deutsch.txt -text +uMod2/uMod_GUI/bin/README_English.txt -text +uMod2/uMod_GUI/bin/languages/Example_uMod_LanguagePack_English.txt -text +uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Deutsch.txt -text +uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_French.txt -text +uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Russian.txt -text +uMod2/uMod_GUI/config.gcc -text +uMod2/uMod_GUI/config.vc -text +uMod2/uMod_GUI/makefile.gcc -text +uMod2/uMod_GUI/makefile.vc -text +uMod2/uMod_GUI/uMod.ico -text +uMod2/uMod_GUI/uMod.rc -text +uMod2/uMod_GUI/uMod_AddTexture.cpp -text +uMod2/uMod_GUI/uMod_AddTexture.h -text +uMod2/uMod_GUI/uMod_Client.cpp -text +uMod2/uMod_GUI/uMod_Client.h -text +uMod2/uMod_GUI/uMod_DirectInjection.cpp -text +uMod2/uMod_GUI/uMod_DirectInjection.h -text +uMod2/uMod_GUI/uMod_Event.cpp -text +uMod2/uMod_GUI/uMod_Event.h -text +uMod2/uMod_GUI/uMod_File.cpp -text +uMod2/uMod_GUI/uMod_File.h -text +uMod2/uMod_GUI/uMod_GUI.cpp -text +uMod2/uMod_GUI/uMod_GUI.h -text +uMod2/uMod_GUI/uMod_GameInfo.cpp -text +uMod2/uMod_GUI/uMod_GameInfo.h -text +uMod2/uMod_GUI/uMod_GamePage.cpp -text +uMod2/uMod_GUI/uMod_GamePage.h -text +uMod2/uMod_GUI/uMod_Language.cpp -text +uMod2/uMod_GUI/uMod_Language.h -text +uMod2/uMod_GUI/uMod_Main.h -text +uMod2/uMod_GUI/uMod_Sender.cpp -text +uMod2/uMod_GUI/uMod_Sender.h -text +uMod2/uMod_GUI/uMod_Server.cpp -text +uMod2/uMod_GUI/uMod_Server.h -text +uMod2/uMod_GUI/uMod_Settings.cpp -text +uMod2/uMod_GUI/uMod_Settings.h -text +uMod2/uMod_GUI/unzip.cpp -text +uMod2/uMod_GUI/unzip.h -text +uMod2/uMod_GUI/zip.cpp -text +uMod2/uMod_GUI/zip.h -text +uMod2/uMod_GlobalDefines.h -text uMod_DX9/makefile.gcc -text uMod_DX9/makefile.vc -text uMod_DX9/uMod_ArrayHandler.cpp -text diff --git a/uMod2/.cproject b/uMod2/.cproject new file mode 100644 index 0000000..c53c9a5 --- /dev/null +++ b/uMod2/.cproject @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/uMod2/.project b/uMod2/.project new file mode 100644 index 0000000..c62d3ee --- /dev/null +++ b/uMod2/.project @@ -0,0 +1,71 @@ + + + uMod + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:/uMod/Debug} + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/uMod2/README.txt b/uMod2/README.txt new file mode 100644 index 0000000..8a62932 --- /dev/null +++ b/uMod2/README.txt @@ -0,0 +1,58 @@ +The licence is set for each file separately. + + +1) How to compile the GUI: + +1.1) You need: +- wxWidgets 2.9. (an earlier version won't work, cause I use wxString functions only available in 2.9., I use atm 2.9.2) + +In the package a makefile for the gcc (makefile.gcc) and a makefile for the MS Visual C Compiler (makefile.vc) is included, but you can generate your own makefile for the compiler of your choice. + +Compiling wxWidgets: +- Compile it with BUILD=release otherwise the executable will be very large. +- The vc compiler somehow generates a smaller executable. +- Set the linkage to static (in the config.gcc or config.vc) before you compile the wxWidgets, to ensure, that also on other PC's your executable will run. + +If you use my makefiles, you have to change the WX_DIR Variable to your wxWidgets directory. This Variable is nearly at the beginning of the makefiles. +note: I have set the linkage to static in the corresponding config.* files, if you have not compiled you wxWidgets with static linkage the compiler will fail, when linking the GUI. + +1.2) Using gcc: +change in the uMod_GUI Directory and type: +mingw32-make -f makefile.gcc BUILD=release +(note: with the options -j 4 you compile simultaneously with 4 threads) + +1.3) Using vc: +change in the uMod_GUI Directory and type: +nmake -f makefile.vc BUILD=release +(note: you need to use the special MS Visual prompt) + + +2) How to compile the dll: + +2.1) You need: +- The DirectX SDK (I use June 2010) +- MS Visual C Compiler (I use the free Express 2010 version) +- maybe the Microsoft Windows SDK + +There exist two makefiles, one for the mingw32-make.exe (makefile.gcc) which call the vc compiler and one for the nmake.exe (makefile.vc) which also calls the vc compiler. I have created the makefile.gcc only to use the -j 4 option of the gnu make. + +You have to compile the 3 dll's separately (one for each injection method). The dll will be copied after successful compilation in the uMod_GUI/bin directory. + +If you want to use the logging mode of the dll you have to parse LOG_MESSAGE=1 + + +2.2) Using gcc (BUT you need the vc compiler!): +change in the uMod_DX9 Directory and type: +mingw32-make -f makefile.gcc +mingw32-make -f makefile.gcc DI=1 +mingw32-make -f makefile.gcc NI=1 +(note: you need to use the special MS Visual prompt) +(note: with the options -j 4 you compile simultaneously with 4 threads) + + +2.3) Using vc: +change in the uMod_DX9 Directory and type: +nmake -f makefile.vc +nmake -f makefile.vc DI=1 +nmake -f makefile.vc NI=1 +(note: you need to use the special MS Visual prompt) \ No newline at end of file diff --git a/uMod2/uMod_DX9/makefile.gcc b/uMod2/uMod_DX9/makefile.gcc new file mode 100644 index 0000000..1a8c827 --- /dev/null +++ b/uMod2/uMod_DX9/makefile.gcc @@ -0,0 +1,117 @@ +ifdef NI + +ifdef LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "NO_INJECTION" +else +precompiler_flag = /D "NO_INJECTION" +endif + +def_file = /DEF:"uMod_DX9_dll_NO_INJECTION.def" +obj_suff = NI.obj +dll = d3d9.dll + +else + +ifdef DI +ifdef LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "DIRECT_INJECTION" +else +precompiler_flag = /D "DIRECT_INJECTION" +endif + +def_file = /DEF:"uMod_DX9_dll_DIRECT_INJECTION.def" +obj_suff = DI.obj +dll = uMod_d3d9_DI.dll + +else + +ifdef LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "HOOK_INJECTION" +else +precompiler_flag = /D "HOOK_INJECTION" +endif + +def_file = /DEF:"uMod_DX9_dll_HOOK_INJECTION.def" +obj_suff = HI.obj +dll = uMod_d3d9_HI.dll +endif +endif + + +CXX = cl +CLINK = link.exe +DEFINES = /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "_WINDLL" /D "_MBCS" +CFLAGS = /I "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include" /nologo /W3 /WX- /O2 ${DEFINES} ${precompiler_flag} /Gm- /EHsc /MT /GS /fp:precise /Zc:wchar_t +LFLAGS = /INCREMENTAL:NO /NOLOGO /LIBPATH:"C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86" /DLL "Winmm.lib" "d3dx9.lib" "dxguid.lib" "user32.lib" "Kernel32.lib" ${def_file} /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE:NO /NXCOMPAT:NO /MACHINE:X86 + +obj = obj +bin = bin + +objects = ${obj}\uMod_DX9_dll.${obj_suff} \ + ${obj}\uMod_IDirect3D9.${obj_suff} \ + ${obj}\uMod_IDirect3D9Ex.${obj_suff} \ + ${obj}\uMod_IDirect3DDevice9.${obj_suff} \ + ${obj}\uMod_IDirect3DDevice9Ex.${obj_suff} \ + ${obj}\uMod_TextureFunction.${obj_suff} \ + ${obj}\uMod_IDirect3DTexture9.${obj_suff} \ + ${obj}\uMod_IDirect3DVolumeTexture9.${obj_suff} \ + ${obj}\uMod_IDirect3DCubeTexture9.${obj_suff} \ + ${obj}\uMod_ArrayHandler.${obj_suff} \ + ${obj}\uMod_TextureClient.${obj_suff} \ + ${obj}\uMod_TextureServer.${obj_suff} + +headers = uMod_Main.h \ + uMod_Defines.h \ + uMod_DX9_dll.h \ + uMod_IDirect3D9.h \ + uMod_IDirect3DDevice9.h \ + uMod_TextureFunction.h \ + uMod_IDirect3DTexture9.h \ + uMod_IDirect3DVolumeTexture9.h \ + uMod_IDirect3DCubeTexture9.h \ + uMod_ArrayHandler.h \ + uMod_TextureClient.h \ + uMod_TextureServer.h + +${bin}\d3d9.dll: ${objects} + ${CLINK} ${LFLAGS} ${objects} /OUT:${bin}\${dll} + copy ${bin}\${dll} ..\uMod_GUI\bin\${dll} + +${obj}\uMod_DX9_dll.${obj_suff}: uMod_DX9_dll.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3D9.${obj_suff}: uMod_IDirect3D9.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3D9Ex.${obj_suff}: uMod_IDirect3D9Ex.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3DDevice9.${obj_suff}: uMod_IDirect3DDevice9.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3DDevice9Ex.${obj_suff}: uMod_IDirect3DDevice9Ex.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_TextureFunction.${obj_suff}: uMod_TextureFunction.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3DTexture9.${obj_suff}: uMod_IDirect3DTexture9.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3DVolumeTexture9.${obj_suff}: uMod_IDirect3DVolumeTexture9.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_IDirect3DCubeTexture9.${obj_suff}: uMod_IDirect3DCubeTexture9.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_ArrayHandler.${obj_suff}: uMod_ArrayHandler.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_TextureClient.${obj_suff}: uMod_TextureClient.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +${obj}\uMod_TextureServer.${obj_suff}: uMod_TextureServer.cpp ${headers} + ${CXX} ${CFLAGS} /c $< /Fo$@ + +clean: + del ${objects} ${bin}\${dll} \ No newline at end of file diff --git a/uMod2/uMod_DX9/makefile.vc b/uMod2/uMod_DX9/makefile.vc new file mode 100644 index 0000000..158175a --- /dev/null +++ b/uMod2/uMod_DX9/makefile.vc @@ -0,0 +1,117 @@ +!IFDEF NI + +!IFDEF LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "NO_INJECTION" +!ELSE +precompiler_flag = /D "NO_INJECTION" +!ENDIF + +def_file = /DEF:"uMod_DX9_dll_NO_INJECTION.def" +obj_suff = NI.obj +dll = d3d9.dll + +!ELSE + +!IFDEF DI +!IFDEF LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "DIRECT_INJECTION" +!ELSE +precompiler_flag = /D "DIRECT_INJECTION" +!ENDIF + +def_file = /DEF:"uMod_DX9_dll_DIRECT_INJECTION.def" +obj_suff = DI.obj +dll = uMod_d3d9_DI.dll + +!ELSE + +!IFDEF LOG_MESSAGE +precompiler_flag = /D "LOG_MESSAGE" /D "HOOK_INJECTION" +!ELSE +precompiler_flag = /D "HOOK_INJECTION" +!ENDIF + +def_file = /DEF:"uMod_DX9_dll_HOOK_INJECTION.def" +obj_suff = HI.obj +dll = uMod_d3d9_HI.dll + +!ENDIF + + +CXX = cl +CLINK = link.exe +DEFINES = /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "_WINDLL" /D "_MBCS" +CFLAGS = /I "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include" /nologo /W3 /WX- /O2 $(DEFINES) $(precompiler_flag) /Gm- /EHsc /MT /GS /fp:precise /Zc:wchar_t +LFLAGS = /INCREMENTAL:NO /NOLOGO /LIBPATH:"C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86" /DLL "Winmm.lib" "d3dx9.lib" "dxguid.lib" "user32.lib" "Kernel32.lib" $(def_file) /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE:NO /NXCOMPAT:NO /MACHINE:X86 + +obj = obj +bin = bin + +objects = $(obj)\uMod_DX9_dll.$(obj_suff) \ + $(obj)\uMod_IDirect3D9.$(obj_suff) \ + $(obj)\uMod_IDirect3D9Ex.$(obj_suff) \ + $(obj)\uMod_IDirect3DDevice9.$(obj_suff) \ + $(obj)\uMod_IDirect3DDevice9Ex.$(obj_suff) \ + $(obj)\uMod_TextureFunction.$(obj_suff) \ + $(obj)\uMod_IDirect3DTexture9.$(obj_suff) \ + $(obj)\uMod_IDirect3DVolumeTexture9.$(obj_suff) \ + $(obj)\uMod_IDirect3DCubeTexture9.$(obj_suff) \ + $(obj)\uMod_ArrayHandler.$(obj_suff) \ + $(obj)\uMod_TextureClient.$(obj_suff) \ + $(obj)\uMod_TextureServer.$(obj_suff) + +headers = uMod_Main.h \ + uMod_Defines.h \ + uMod_DX9_dll.h \ + uMod_IDirect3D9.h \ + uMod_IDirect3DDevice9.h \ + uMod_TextureFunction.h \ + uMod_IDirect3DTexture9.h \ + uMod_IDirect3DVolumeTexture9.h \ + uMod_IDirect3DCubeTexture9.h \ + uMod_ArrayHandler.h \ + uMod_TextureClient.h \ + uMod_TextureServer.h + +$(bin)\d3d9.dll: $(objects) + $(CLINK) $(LFLAGS) $(objects) /OUT:$(bin)\$(dll) + copy $(bin)\$(dll) ..\uMod_GUI\bin\$(dll) + +$(obj)\uMod_DX9_dll.$(obj_suff): uMod_DX9_dll.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_DX9_dll.cpp + +$(obj)\uMod_IDirect3D9.$(obj_suff): uMod_IDirect3D9.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3D9.cpp + +$(obj)\uMod_IDirect3D9Ex.$(obj_suff): uMod_IDirect3D9Ex.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3D9Ex.cpp + +$(obj)\uMod_IDirect3DDevice9.$(obj_suff): uMod_IDirect3DDevice9.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3DDevice9.cpp + +$(obj)\uMod_IDirect3DDevice9Ex.$(obj_suff): uMod_IDirect3DDevice9Ex.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3DDevice9Ex.cpp + +$(obj)\uMod_TextureFunction.$(obj_suff): uMod_TextureFunction.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_TextureFunction.cpp + +$(obj)\uMod_IDirect3DTexture9.$(obj_suff): uMod_IDirect3DTexture9.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3DTexture9.cpp + +$(obj)\uMod_IDirect3DVolumeTexture9.$(obj_suff): uMod_IDirect3DVolumeTexture9.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3DVolumeTexture9.cpp + +$(obj)\uMod_IDirect3DCubeTexture9.$(obj_suff): uMod_IDirect3DCubeTexture9.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_IDirect3DCubeTexture9.cpp + +$(obj)\uMod_ArrayHandler.$(obj_suff): uMod_ArrayHandler.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_ArrayHandler.cpp + +$(obj)\uMod_TextureClient.$(obj_suff): uMod_TextureClient.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_TextureClient.cpp + +$(obj)\uMod_TextureServer.$(obj_suff): uMod_TextureServer.cpp $(headers) + $(CXX) $(CFLAGS) /c /Fo$@ uMod_TextureServer.cpp + +clean: + del $(objects) $(bin)\$(dll) \ No newline at end of file diff --git a/uMod2/uMod_DX9/uMod_ArrayHandler.cpp b/uMod2/uMod_DX9/uMod_ArrayHandler.cpp new file mode 100644 index 0000000..add6aca --- /dev/null +++ b/uMod2/uMod_DX9/uMod_ArrayHandler.cpp @@ -0,0 +1,106 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + + +#include "uMod_Main.h" + + + + + +uMod_FileHandler::uMod_FileHandler(void) +{ + Message("uMod_FileHandler(void): %lu\n", this); + Number = 0; + FieldCounter = 0; + Files = NULL; +} + +uMod_FileHandler::~uMod_FileHandler(void) +{ + Message("~uMod_FileHandler(void): %lu\n", this); + if (Files!=NULL) + { + for (int i=0; iReference>=0) return (RETURN_UPDATE_ALLREADY_ADDED); + + if (Number/FieldLength==FieldCounter) // get more memory + { + TextureFileStruct*** temp = NULL; + try {temp = new TextureFileStruct**[FieldCounter+10];} + catch (...) + { + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_TEXTURE; + return (RETURN_NO_MEMORY); + } + + for (int i=0; iReference = Number++; //set the reference for a fast deleting + + return (RETURN_OK); +} + + +int uMod_FileHandler::Remove(TextureFileStruct* file) +{ + Message("uMod_FileHandler::Remove(%lu): %lu\n", file, this); + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + int ref = file->Reference; + + if (ref<0) return (RETURN_OK); // returning if no Reference is set + file->Reference = -1; //set reference outside of bound + if (ref<(--Number)) //if reference is unequal to Number-1 we copy the last entry to the index "ref" + { + Files[ref/FieldLength][ref%FieldLength] = Files[Number/FieldLength][Number%FieldLength]; + Files[ref/FieldLength][ref%FieldLength]->Reference = ref; //set the new reference entry + } + return (RETURN_OK); +} + diff --git a/uMod2/uMod_DX9/uMod_ArrayHandler.h b/uMod2/uMod_DX9/uMod_ArrayHandler.h new file mode 100644 index 0000000..c8b6fd7 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_ArrayHandler.h @@ -0,0 +1,185 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_FIELDHANDLER_H_ +#define uMod_FIELDHANDLER_H_ + +#include "..\uMod_GlobalDefines.h" +#include "uMod_IDirect3DTexture9.h" + +typedef struct +{ + bool ForceReload; // to force a reload of the texture (if it is already modded) + char* pData; // store texture file as file in memory + unsigned int Size; // size of file + int NumberOfTextures; + int Reference; // for a fast delete in the FileHandler + IDirect3DBaseTexture9 **Textures; // pointer to the fake textures + MyTypeHash Hash; // hash value +} TextureFileStruct; + + + +class uMod_FileHandler // array to store TextureFileStruct +{ +public: + uMod_FileHandler(void); + ~uMod_FileHandler(void); + + int Add( TextureFileStruct* file); + int Remove( TextureFileStruct* file); + + int GetNumber(void) {return (Number);} + + TextureFileStruct *operator [] (int i) {if (i<0||i>=Number) return (NULL); else return (Files[i/FieldLength][i%FieldLength]);} + +protected: + static const int FieldLength = 1024; + long Number; + int FieldCounter; + TextureFileStruct*** Files; +}; + + + +template +class uMod_TextureHandler // array to store uMod_IDirect3DTexture9, uMod_IDirect3DVolumeTexture9 or uMod_IDirect3DCubeTexture9 +{ +public: + uMod_TextureHandler(void); + ~uMod_TextureHandler(void); + + int Add( T* texture); + int Remove( T* texture); + + int GetNumber(void) {return (Number);} + T *operator [] (int i) {if (i<0||i>=Number) return (NULL); else return (Textures[i/FieldLength][i%FieldLength]);} + +private: + static const int FieldLength = 1024; + long Number; + int FieldCounter; + T*** Textures; +}; + + + + + + + + + + + + + +template +uMod_TextureHandler::uMod_TextureHandler(void) +{ + Message("uMod_TextureHandler(void): %lu\n", this); + Number = 0; + FieldCounter = 0; + + Textures = NULL; +} + +template +uMod_TextureHandler::~uMod_TextureHandler(void) +{ + Message("~uMod_TextureHandler(void): %lu\n", this); + if (Textures!=NULL) + { + for (int i=0; i +int uMod_TextureHandler::Add(T* pTexture) +{ + Message("uMod_TextureHandler::Add( %lu): %lu\n", pTexture, this); + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + if (pTexture->Reference>=0) return (RETURN_TEXTURE_ALLREADY_ADDED); + + if (Number/FieldLength==FieldCounter) + { + T*** temp = NULL; + try {temp = new T**[FieldCounter+10];} + catch (...) + { + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_TEXTURE; + return (RETURN_NO_MEMORY); + } + + for (int i=0; iReference = Number++; + + return (RETURN_OK); +} + + +template +int uMod_TextureHandler::Remove(T* pTexture) //will be called, if a texture is completely released +{ + Message("uMod_TextureHandler::Remove( %lu): %lu\n", pTexture, this); + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + int ref = pTexture->Reference; + if (ref<0|| ref>=Number) return (RETURN_OK); // it is not in this list + if (Textures[ref/FieldLength][ref%FieldLength]!=pTexture) return (RETURN_OK); // it is not in this list + + if (ref<(--Number)) + { + Textures[ref/FieldLength][ref%FieldLength] = Textures[Number/FieldLength][Number%FieldLength]; + Textures[ref/FieldLength][ref%FieldLength]->Reference = ref; + } + pTexture->Reference = -1; + return (RETURN_OK); +} + + + + + + +#endif /* uMod_FIELDHANDLER_H_ */ diff --git a/uMod2/uMod_DX9/uMod_DX9_dll.cpp b/uMod2/uMod_DX9/uMod_DX9_dll.cpp new file mode 100644 index 0000000..1b6e62b --- /dev/null +++ b/uMod2/uMod_DX9/uMod_DX9_dll.cpp @@ -0,0 +1,516 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + + + NEVER USE THIS CODE FOR ILLEGAL PURPOSE + + +*/ + + +#include "uMod_Main.h" +//#include "detours.h" +//#include "detourxs/detourxs/detourxs.h" + +/* +#include "detourxs/detourxs/ADE32.cpp" +#include "detourxs/detourxs/detourxs.cpp" +*/ +/* + * global variable which are not linked external + */ +HINSTANCE gl_hOriginalDll = NULL; +HINSTANCE gl_hThisInstance = NULL; +uMod_TextureServer* gl_TextureServer = NULL; +HANDLE gl_ServerThread = NULL; + +typedef IDirect3D9 *(APIENTRY *Direct3DCreate9_type)(UINT); +typedef HRESULT (APIENTRY *Direct3DCreate9Ex_type)(UINT SDKVersion, IDirect3D9Ex **ppD3D); + +#ifndef NO_INJECTION +Direct3DCreate9_type Direct3DCreate9_fn; // we need to store the pointer to the original Direct3DCreate9 function after we have done a detour +Direct3DCreate9Ex_type Direct3DCreate9Ex_fn; // we need to store the pointer to the original Direct3DCreate9 function after we have done a detour +HHOOK gl_hHook = NULL; +#endif + + + + +/* + * global variable which are linked external + */ +unsigned int gl_ErrorState = 0u; + +#ifdef LOG_MESSAGE +FILE* gl_File = NULL; +#endif + + +#ifdef DIRECT_INJECTION +void Nothing(void) {(void)NULL;} +#endif +/* + * dll entry routine, here we initialize or clean up + */ +BOOL WINAPI DllMain( HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + UNREFERENCED_PARAMETER(lpReserved); + + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + InitInstance(hModule); + break; + } + case DLL_PROCESS_DETACH: + { + ExitInstance(); + break; + } + default: break; + } + + return (true); +} + + +DWORD WINAPI ServerThread( LPVOID lpParam ) +{ + UNREFERENCED_PARAMETER(lpParam); + if (gl_TextureServer!=NULL) gl_TextureServer->MainLoop(); //This is and endless mainloop, it sleep till something is written into the pipe. + return (0); +} + +void InitInstance(HINSTANCE hModule) +{ + + DisableThreadLibraryCalls( hModule ); //reduce overhead + + gl_hThisInstance = (HINSTANCE) hModule; + + wchar_t game[MAX_PATH]; + if (HookThisProgram( game)) //ask if we need to hook this program + { + OpenMessage(); + Message("InitInstance: %lu\n", hModule); + + gl_TextureServer = new uMod_TextureServer(game); //create the server which listen on the pipe and prepare the update for the texture clients + + LoadOriginalDll(); + +#ifndef NO_INJECTION + // we detour the original Direct3DCreate9 to our MyDirect3DCreate9 + Direct3DCreate9_fn = (Direct3DCreate9_type) GetProcAddress(gl_hOriginalDll, "Direct3DCreate9"); + if (Direct3DCreate9_fn!=NULL) + { + Message("Detour: Direct3DCreate9\n"); + Direct3DCreate9_fn = (Direct3DCreate9_type)DetourFunc( (BYTE*)Direct3DCreate9_fn, (BYTE*)uMod_Direct3DCreate9, 5); + } + + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type) GetProcAddress(gl_hOriginalDll, "Direct3DCreate9Ex"); + if (Direct3DCreate9Ex_fn!=NULL) + { + Message("Detour: Direct3DCreate9Ex\n"); + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type)DetourFunc( (BYTE*)Direct3DCreate9Ex_fn, (BYTE*)uMod_Direct3DCreate9Ex, 7); + } +#endif + + if (gl_TextureServer->OpenPipe(game)) //open the pipe and send the name+path of this executable + { + Message("InitInstance: Pipe not opened\n"); + return; + } + + gl_ServerThread = CreateThread( NULL, 0, ServerThread, NULL, 0, NULL); //creating a thread for the mainloop + if (gl_ServerThread==NULL) {Message("InitInstance: Serverthread not started\n");} + + } +} + +void LoadOriginalDll(void) +{ + char buffer[MAX_PATH]; + GetSystemDirectory(buffer,MAX_PATH); //get the system directory, we need to open the original d3d9.dll + + // Append dll name + strcat_s( buffer, MAX_PATH,"\\d3d9.dll"); + + // try to load the system's d3d9.dll, if pointer empty + if (!gl_hOriginalDll) gl_hOriginalDll = LoadLibrary(buffer); + + if (!gl_hOriginalDll) + { + ExitProcess(0); // exit the hard way + } +} + +void ExitInstance() +{ + if (gl_TextureServer!=NULL) + { + gl_TextureServer->ClosePipe(); //This must be done before the server thread is killed, because the server thread will endless wait on the ReadFile() + } + if (gl_ServerThread!=NULL) + { + CloseHandle(gl_ServerThread); // kill the server thread + gl_ServerThread = NULL; + } + if (gl_TextureServer!=NULL) + { + delete gl_TextureServer; //delete the texture server + gl_TextureServer = NULL; + } + + // Release the system's d3d9.dll + if (gl_hOriginalDll!=NULL) + { + FreeLibrary(gl_hOriginalDll); + gl_hOriginalDll = NULL; + } + + CloseMessage(); +} + +#ifdef NO_INJECTION +/* + * We do not inject, the game loads this dll by itself thus we must include the Direct3DCreate9 function + */ + +IDirect3D9* WINAPI Direct3DCreate9(UINT SDKVersion) +{ + Message("WINAPI Direct3DCreate9\n"); + + if (!gl_hOriginalDll) LoadOriginalDll(); // looking for the "right d3d9.dll" + + // find original function in original d3d9.dll + Direct3DCreate9_type D3DCreate9_fn = (Direct3DCreate9_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9"); + + + if (!D3DCreate9_fn) + { + Message("Direct3DCreate9: original function not found in dll\n"); + return (NULL); + } + + + //Create originale IDirect3D9 object + IDirect3D9 *pIDirect3D9_orig = D3DCreate9_fn(SDKVersion); + + //create our uMod_IDirect3D9 object + uMod_IDirect3D9 *pIDirect3D9 = new uMod_IDirect3D9( pIDirect3D9_orig, gl_TextureServer); + + // Return pointer to our object instead of "real one" + return (pIDirect3D9); +} + +HRESULT WINAPI Direct3DCreate9Ex(UINT SDKVersion, IDirect3D9Ex **ppD3D) +{ + Message("WINAPI Direct3DCreate9Ex\n"); + + if (!gl_hOriginalDll) LoadOriginalDll(); // looking for the "right d3d9.dll" + + // find original function in original d3d9.dll + Direct3DCreate9Ex_type D3DCreate9Ex_fn = (Direct3DCreate9Ex_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9Ex"); + + + if (!D3DCreate9Ex_fn) + { + Message("Direct3DCreate9Ex: original function not found in dll\n"); + return (D3DERR_NOTAVAILABLE); + } + + + //Create originale IDirect3D9 object + IDirect3D9Ex *pIDirect3D9Ex_orig; + HRESULT ret = D3DCreate9Ex_fn( SDKVersion, &pIDirect3D9Ex_orig); + if (ret!=S_OK) return (ret); + + //create our uMod_IDirect3D9 object + uMod_IDirect3D9Ex *pIDirect3D9Ex = new uMod_IDirect3D9Ex( pIDirect3D9Ex_orig, gl_TextureServer); + + ppD3D = &pIDirect3D9Ex_orig; // Return pointer to our object instead of "real one" + return (ret); +} + +typedef IDirect3D9 *(APIENTRY *Direct3DCreate9_type)(UINT); +typedef HRESULT (APIENTRY *Direct3DCreate9Ex_type)(UINT SDKVersion, IDirect3D9Ex **ppD3D); + +typedef int (WINAPI *D3DPERF_BeginEvent_type)( D3DCOLOR , LPCWSTR ); +int WINAPI D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ) +{ + D3DPERF_BeginEvent_type fn = (D3DPERF_BeginEvent_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_BeginEvent"); + return fn( col, wszName); +} + +typedef int (WINAPI *D3DPERF_EndEvent_type)( void ); +int WINAPI D3DPERF_EndEvent( void ) +{ + D3DPERF_EndEvent_type fn = (D3DPERF_EndEvent_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_EndEvent"); + return fn(); +} + +typedef void (WINAPI *D3DPERF_SetMarker_type)( D3DCOLOR , LPCWSTR ); +void WINAPI D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName ) +{ + D3DPERF_SetMarker_type fn = (D3DPERF_SetMarker_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_SetMarker"); + return fn( col, wszName); +} + +typedef void (WINAPI *D3DPERF_SetRegion_type)( D3DCOLOR, LPCWSTR ); +void WINAPI D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName ) +{ + D3DPERF_SetRegion_type fn = (D3DPERF_SetRegion_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_SetRegion"); + return fn( col, wszName); +} + +typedef BOOL (WINAPI *D3DPERF_QueryRepeatFrame_type)( void ); +BOOL WINAPI D3DPERF_QueryRepeatFrame( void ) +{ + D3DPERF_QueryRepeatFrame_type fn = (D3DPERF_QueryRepeatFrame_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_QueryRepeatFrame"); + return fn( ); +} + +typedef void (WINAPI *D3DPERF_SetOptions_type)( DWORD ); +void WINAPI D3DPERF_SetOptions( DWORD dwOptions ) +{ + D3DPERF_SetOptions_type fn = (D3DPERF_SetOptions_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_SetOptions"); + return fn( dwOptions); +} + +typedef DWORD (WINAPI *D3DPERF_GetStatus_type)( void ); +DWORD WINAPI D3DPERF_GetStatus( void ) +{ + D3DPERF_GetStatus_type fn = (D3DPERF_GetStatus_type) GetProcAddress( gl_hOriginalDll, "D3DPERF_GetStatus"); + return fn( ); +} + + +bool HookThisProgram( wchar_t *ret) //this function always return true, it is needed for the name and path of the executable +{ + wchar_t Executable[MAX_PATH]; + GetModuleFileNameW( GetModuleHandle( NULL ), Executable, MAX_PATH ); //ask for name and path of this executable + + int len = 0; + while (Executable[len]) {ret[len] = Executable[len]; len++;} + ret[len] = 0; + return (true); +} + + + +#else + +/* + * We inject the dll into the game, thus we retour the original Direct3DCreate9 function to our MyDirect3DCreate9 function + */ + +IDirect3D9 *APIENTRY uMod_Direct3DCreate9(UINT SDKVersion) +{ + Message("uMod_Direct3DCreate9: original %lu, uMod %lu\n", Direct3DCreate9_fn, uMod_Direct3DCreate9); + + // in the Internet are many tutorials for detouring functions and all of them will work without the following 5 marked lines + // but somehow, for me it only works, if I retour the function and calling afterward the original function + + // BEGIN + + LoadOriginalDll(); + + RetourFunc((BYTE*) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9"), (BYTE*)Direct3DCreate9_fn, 5); + Direct3DCreate9_fn = (Direct3DCreate9_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9"); + +/* + if (Direct3DCreate9Ex_fn!=NULL) + { + RetourFunc((BYTE*) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9Ex"), (BYTE*)Direct3DCreate9Ex_fn, 7); + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9Ex"); + } + */ + // END + + IDirect3D9 *pIDirect3D9_orig = NULL; + if (Direct3DCreate9_fn) + { + pIDirect3D9_orig = Direct3DCreate9_fn(SDKVersion); //creating the original IDirect3D9 object + } + else return (NULL); + uMod_IDirect3D9 *pIDirect3D9; + if (pIDirect3D9_orig) + { + pIDirect3D9 = new uMod_IDirect3D9( pIDirect3D9_orig, gl_TextureServer); //creating our uMod_IDirect3D9 object + } + + // we detour again + Direct3DCreate9_fn = (Direct3DCreate9_type)DetourFunc( (BYTE*) Direct3DCreate9_fn, (BYTE*)uMod_Direct3DCreate9,5); + /* + if (Direct3DCreate9Ex_fn!=NULL) + { + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type)DetourFunc( (BYTE*) Direct3DCreate9Ex_fn, (BYTE*)uMod_Direct3DCreate9Ex,7); + } +*/ + return (pIDirect3D9); //return our object instead of the "real one" +} + +HRESULT APIENTRY uMod_Direct3DCreate9Ex( UINT SDKVersion, IDirect3D9Ex **ppD3D) +{ + Message( "uMod_Direct3DCreate9Ex: original %lu, uMod %lu\n", Direct3DCreate9Ex_fn, uMod_Direct3DCreate9Ex); + + // in the Internet are many tutorials for detouring functions and all of them will work without the following 5 marked lines + // but somehow, for me it only works, if I retour the function and calling afterward the original function + + // BEGIN + + LoadOriginalDll(); + /* + if (Direct3DCreate9_fn!=NULL) + { + RetourFunc((BYTE*) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9"), (BYTE*)Direct3DCreate9_fn, 5); + Direct3DCreate9_fn = (Direct3DCreate9_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9"); + } +*/ + RetourFunc((BYTE*) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9Ex"), (BYTE*)Direct3DCreate9Ex_fn, 7); + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9Ex"); + // END + + IDirect3D9Ex *pIDirect3D9Ex_orig = NULL; + HRESULT ret; + if (Direct3DCreate9Ex_fn) + { + ret = Direct3DCreate9Ex_fn(SDKVersion, &pIDirect3D9Ex_orig); //creating the original IDirect3D9 object + } + else return (D3DERR_NOTAVAILABLE); + + if (ret!=S_OK) return (ret); + + uMod_IDirect3D9Ex *pIDirect3D9Ex; + if (pIDirect3D9Ex_orig) + { + pIDirect3D9Ex = new uMod_IDirect3D9Ex( pIDirect3D9Ex_orig, gl_TextureServer); //creating our uMod_IDirect3D9 object + } + + // we detour again +/* + if (Direct3DCreate9_fn!=NULL) + { + Direct3DCreate9_fn = (Direct3DCreate9_type)DetourFunc( (BYTE*) Direct3DCreate9_fn, (BYTE*)uMod_Direct3DCreate9,5); + } + */ + Direct3DCreate9Ex_fn = (Direct3DCreate9Ex_type)DetourFunc( (BYTE*) Direct3DCreate9Ex_fn, (BYTE*)uMod_Direct3DCreate9Ex,7); + ppD3D = (IDirect3D9Ex**) &pIDirect3D9Ex; //return our object instead of the "real one" + return (ret); +} + +bool HookThisProgram( wchar_t *ret) +{ + wchar_t Executable[MAX_PATH]; + wchar_t Game[MAX_PATH]; + GetModuleFileNameW( GetModuleHandle( NULL ), Executable, MAX_PATH ); //ask for name and path of this executable + +#ifdef HOOK_INJECTION + //we use the gloabal hook + + FILE* file; + wchar_t *app_path = _wgetenv( L"APPDATA"); //asc for the user application directory + wchar_t file_name[MAX_PATH]; + swprintf_s( file_name, MAX_PATH, L"%ls\\%ls\\%ls", app_path, uMod_APP_DIR, uMod_APP_DX9); + if (_wfopen_s( &file, file_name, L"rt,ccs=UTF-16LE")) return (false); // open the file in utf-16 LE mode + + + //MessageBoxW( NULL, Executable, L"test", 0); + while (!feof(file)) + { + if ( fgetws( Game, MAX_PATH, file) != NULL ) //get each line of the file + { + //MessageBoxW( NULL, Game, L"test", 0); + int len = 0; + while (Game[len]) + { + if (Game[len]==L'\r' || Game[len]==L'\n') {Game[len]=0; break;} //removing the new line symbols + len++; + } + if ( _wcsicmp( Executable, Game ) == 0 ) //compare both strings + { + for (int i=0; i. +*/ + + + +#ifndef uMod_DX9_DLL_H_ +#define uMod_DX9_DLL_H_ + +void InitInstance(HINSTANCE hModule); +void ExitInstance(void); +void LoadOriginalDll(void); +bool HookThisProgram( wchar_t *ret); +DWORD WINAPI ServerThread( LPVOID lpParam); + + + +#ifndef NO_INJECTION + +void *DetourFunc(BYTE *src, const BYTE *dst, const int len); +bool RetourFunc(BYTE *src, BYTE *restore, const int len); +IDirect3D9 *APIENTRY uMod_Direct3DCreate9(UINT SDKVersion); +HRESULT APIENTRY uMod_Direct3DCreate9Ex( UINT SDKVersion, IDirect3D9Ex **ppD3D); + +#ifdef HOOK_INJECTION +LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam); +void InstallHook(void); +void RemoveHook(void); +#endif + + +#ifdef DIRECT_INJECTION +void Nothing(void); +#endif + +#endif + +#endif diff --git a/uMod2/uMod_DX9/uMod_DX9_dll_DIRECT_INJECTION.def b/uMod2/uMod_DX9/uMod_DX9_dll_DIRECT_INJECTION.def new file mode 100644 index 0000000..7a0a69c --- /dev/null +++ b/uMod2/uMod_DX9/uMod_DX9_dll_DIRECT_INJECTION.def @@ -0,0 +1,5 @@ +LIBRARY "uMod_d3d9_DI" +EXPORTS + uMod_Direct3DCreate9 @1 + uMod_Direct3DCreate9Ex @2 + Nothing @3 \ No newline at end of file diff --git a/uMod2/uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def b/uMod2/uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def new file mode 100644 index 0000000..a5cc70c --- /dev/null +++ b/uMod2/uMod_DX9/uMod_DX9_dll_HOOK_INJECTION.def @@ -0,0 +1,6 @@ +LIBRARY "uMod_d3d9_Hook" +EXPORTS + uMod_Direct3DCreate9 @1 + uMod_Direct3DCreate9Ex @2 + InstallHook @3 + RemoveHook @4 \ No newline at end of file diff --git a/uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def b/uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def new file mode 100644 index 0000000..13062a6 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_DX9_dll_NO_INJECTION.def @@ -0,0 +1,13 @@ +LIBRARY "d3d9" +EXPORTS + Direct3DCreate9 @1 + Direct3DCreate9Ex @2 + + D3DPERF_BeginEvent @3 + D3DPERF_EndEvent @4 + D3DPERF_SetMarker @5 + D3DPERF_SetRegion @6 + D3DPERF_QueryRepeatFrame @7 + + D3DPERF_SetOptions @8 + D3DPERF_GetStatus @9 \ No newline at end of file diff --git a/uMod2/uMod_DX9/uMod_Defines.h b/uMod2/uMod_DX9/uMod_Defines.h new file mode 100644 index 0000000..4cf9ff6 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_Defines.h @@ -0,0 +1,70 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_DEFINES_H_ +#define uMod_DEFINES_H_ + + + +#ifdef LOG_MESSAGE +extern FILE *gl_File; + +#define Message(...) {if (gl_File!=NULL) {fprintf( gl_File, __VA_ARGS__); fflush(gl_File);}} +#ifdef HOOK_INJECTION +#define OpenMessage(...) {if (fopen_s( &gl_File, "uMod_log.txt", "wt")) gl_File=NULL; else fprintf( gl_File, "HI R40: 0000002\n");} +#endif + +#ifdef DIRECT_INJECTION +#define OpenMessage(...) {if (fopen_s( &gl_File, "uMod_log.txt", "wt")) gl_File=NULL; else fprintf( gl_File, "DI R40: 0000002\n");} +#endif + +#ifdef NO_INJECTION +#define OpenMessage(...) {if (fopen_s( &gl_File, "uMod_log.txt", "wt")) gl_File=NULL; else fprintf( gl_File, "NI R40: 0000002\n");} +#endif + +#define CloseMessage(...) {if (gl_File!=NULL) fclose(gl_File);} + + +#else +#define OpenMessage(...) +#define Message(...) +#define CloseMessage(...) +#endif + + +#ifdef __CDT_PARSER__ +typedef unsigned long DWORD64; +typedef unsigned long DWORD32; + +#define STDMETHOD(method) virtual HRESULT method +#define STDMETHOD_(ret, method) virtual ret method +#define sprintf_s(...) +#define fprintf(...) +#define fclose(...) +#define fseek(...) +#define ftell(...) 0 +#define fflush(...) +typedef LONG HRESULT; + +#define UNREFERENCED_PARAMETER(...) +#endif + + +#endif /* uMod_DEFINES_H_ */ diff --git a/uMod2/uMod_DX9/uMod_IDirect3D9.cpp b/uMod2/uMod_DX9/uMod_IDirect3D9.cpp new file mode 100644 index 0000000..ac415a4 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3D9.cpp @@ -0,0 +1,156 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + + + +#include "uMod_Main.h" + +#ifndef PRE_MESSAGE +#define PRE_MESSAGE "uMod_IDirect3D9" +#endif + +uMod_IDirect3D9::uMod_IDirect3D9( IDirect3D9 *pOriginal, uMod_TextureServer* server) +{ + Message( PRE_MESSAGE "::" PRE_MESSAGE "( %lu, %lu): %lu\n", pOriginal, server, this); + m_pIDirect3D9 = pOriginal; + uMod_Server = server; +} + +uMod_IDirect3D9::~uMod_IDirect3D9(void) +{ + Message( PRE_MESSAGE "::~" PRE_MESSAGE "(): %lu\n", this); +} + +HRESULT __stdcall uMod_IDirect3D9::QueryInterface(REFIID riid, void** ppvObj) +{ + *ppvObj = NULL; + + // call this to increase AddRef at original object + // and to check if such an interface is there + + HRESULT hRes = m_pIDirect3D9->QueryInterface(riid, ppvObj); + + if (hRes == NOERROR) // if OK, send our "fake" address + { + *ppvObj = this; + } + + return (hRes); +} + +ULONG __stdcall uMod_IDirect3D9::AddRef(void) +{ + return(m_pIDirect3D9->AddRef()); +} + +ULONG __stdcall uMod_IDirect3D9::Release(void) +{ + // call original routine + ULONG count = m_pIDirect3D9->Release(); + + // in case no further Ref is there, the Original Object has deleted itself + if (count == 0) + { + delete(this); + } + + return(count); +} + +HRESULT __stdcall uMod_IDirect3D9::RegisterSoftwareDevice(void* pInitializeFunction) +{ + return(m_pIDirect3D9->RegisterSoftwareDevice(pInitializeFunction)); +} + +UINT __stdcall uMod_IDirect3D9::GetAdapterCount(void) +{ + return(m_pIDirect3D9->GetAdapterCount()); +} + +HRESULT __stdcall uMod_IDirect3D9::GetAdapterIdentifier(UINT Adapter,DWORD Flags,D3DADAPTER_IDENTIFIER9* pIdentifier) +{ + return(m_pIDirect3D9->GetAdapterIdentifier(Adapter,Flags,pIdentifier)); +} + +UINT __stdcall uMod_IDirect3D9::GetAdapterModeCount(UINT Adapter, D3DFORMAT Format) +{ + return(m_pIDirect3D9->GetAdapterModeCount(Adapter, Format)); +} + +HRESULT __stdcall uMod_IDirect3D9::EnumAdapterModes(UINT Adapter,D3DFORMAT Format,UINT Mode,D3DDISPLAYMODE* pMode) +{ + return(m_pIDirect3D9->EnumAdapterModes(Adapter,Format,Mode,pMode)); +} + +HRESULT __stdcall uMod_IDirect3D9::GetAdapterDisplayMode( UINT Adapter,D3DDISPLAYMODE* pMode) +{ + return(m_pIDirect3D9->GetAdapterDisplayMode(Adapter,pMode)); +} + +HRESULT __stdcall uMod_IDirect3D9::CheckDeviceType(UINT iAdapter,D3DDEVTYPE DevType,D3DFORMAT DisplayFormat,D3DFORMAT BackBufferFormat,BOOL bWindowed) +{ + return(m_pIDirect3D9->CheckDeviceType(iAdapter,DevType,DisplayFormat,BackBufferFormat,bWindowed)); +} + +HRESULT __stdcall uMod_IDirect3D9::CheckDeviceFormat(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,DWORD Usage,D3DRESOURCETYPE RType,D3DFORMAT CheckFormat) +{ + return(m_pIDirect3D9->CheckDeviceFormat(Adapter,DeviceType,AdapterFormat,Usage,RType,CheckFormat)); +} + +HRESULT __stdcall uMod_IDirect3D9::CheckDeviceMultiSampleType(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SurfaceFormat,BOOL Windowed,D3DMULTISAMPLE_TYPE MultiSampleType,DWORD* pQualityLevels) +{ + return(m_pIDirect3D9->CheckDeviceMultiSampleType(Adapter,DeviceType,SurfaceFormat,Windowed,MultiSampleType,pQualityLevels)); +} + +HRESULT __stdcall uMod_IDirect3D9::CheckDepthStencilMatch(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,D3DFORMAT RenderTargetFormat,D3DFORMAT DepthStencilFormat) +{ + return(m_pIDirect3D9->CheckDepthStencilMatch(Adapter,DeviceType,AdapterFormat,RenderTargetFormat,DepthStencilFormat)); +} + +HRESULT __stdcall uMod_IDirect3D9::CheckDeviceFormatConversion(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SourceFormat,D3DFORMAT TargetFormat) +{ + return(m_pIDirect3D9->CheckDeviceFormatConversion(Adapter,DeviceType,SourceFormat,TargetFormat)); +} + +HRESULT __stdcall uMod_IDirect3D9::GetDeviceCaps(UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps) +{ + return(m_pIDirect3D9->GetDeviceCaps(Adapter,DeviceType,pCaps)); +} + +HMONITOR __stdcall uMod_IDirect3D9::GetAdapterMonitor(UINT Adapter) +{ + return(m_pIDirect3D9->GetAdapterMonitor(Adapter)); +} + +HRESULT __stdcall uMod_IDirect3D9::CreateDevice(UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface) +{ + Message( PRE_MESSAGE "::CreateDevice(): %lu\n", this); + // we intercept this call and provide our own "fake" Device Object + HRESULT hres = m_pIDirect3D9->CreateDevice( Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); + + int count = 1; + if (pPresentationParameters!=NULL) count = pPresentationParameters->BackBufferCount; + uMod_IDirect3DDevice9 *pIDirect3DDevice9 = new uMod_IDirect3DDevice9(*ppReturnedDeviceInterface, uMod_Server, count); + + // store our pointer (the fake one) for returning it to the calling program + *ppReturnedDeviceInterface = pIDirect3DDevice9; + + return(hres); +} diff --git a/uMod2/uMod_DX9/uMod_IDirect3D9.h b/uMod2/uMod_DX9/uMod_IDirect3D9.h new file mode 100644 index 0000000..b6ff69b --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3D9.h @@ -0,0 +1,66 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + * + * BIG THANKS TO Michael Koch + * (proxydll_9.zip) + * + */ + + +#ifndef uMod_IDirect3D9_H_ +#define uMod_IDirect3D9_H_ + + +#include +#include +#include "uMod_TextureServer.h" +#include "uMod_TextureClient.h" + +class uMod_IDirect3D9 : public IDirect3D9 +{ +public: + uMod_IDirect3D9(IDirect3D9 *pOriginal, uMod_TextureServer *server); + virtual ~uMod_IDirect3D9(void); + + // The original DX9 function definitions + HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); + ULONG __stdcall AddRef(void); + ULONG __stdcall Release(void); + HRESULT __stdcall RegisterSoftwareDevice(void* pInitializeFunction); + UINT __stdcall GetAdapterCount(void); + HRESULT __stdcall GetAdapterIdentifier(UINT Adapter,DWORD Flags,D3DADAPTER_IDENTIFIER9* pIdentifier) ; + UINT __stdcall GetAdapterModeCount(UINT Adapter, D3DFORMAT Format); + HRESULT __stdcall EnumAdapterModes(UINT Adapter,D3DFORMAT Format,UINT Mode,D3DDISPLAYMODE* pMode) ; + HRESULT __stdcall GetAdapterDisplayMode( UINT Adapter,D3DDISPLAYMODE* pMode) ; + HRESULT __stdcall CheckDeviceType(UINT iAdapter,D3DDEVTYPE DevType,D3DFORMAT DisplayFormat,D3DFORMAT BackBufferFormat,BOOL bWindowed) ; + HRESULT __stdcall CheckDeviceFormat(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,DWORD Usage,D3DRESOURCETYPE RType,D3DFORMAT CheckFormat) ; + HRESULT __stdcall CheckDeviceMultiSampleType(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SurfaceFormat,BOOL Windowed,D3DMULTISAMPLE_TYPE MultiSampleType,DWORD* pQualityLevels) ; + HRESULT __stdcall CheckDepthStencilMatch(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,D3DFORMAT RenderTargetFormat,D3DFORMAT DepthStencilFormat) ; + HRESULT __stdcall CheckDeviceFormatConversion(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SourceFormat,D3DFORMAT TargetFormat); + HRESULT __stdcall GetDeviceCaps(UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps) ; + HMONITOR __stdcall GetAdapterMonitor(UINT Adapter) ; + HRESULT __stdcall CreateDevice(UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface) ; + +private: + IDirect3D9 *m_pIDirect3D9; + uMod_TextureServer* uMod_Server; +}; + +#endif diff --git a/uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp b/uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp new file mode 100644 index 0000000..0259b3e --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3D9Ex.cpp @@ -0,0 +1,71 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + + + +#include "uMod_Main.h" + + + +#define IDirect3D9 IDirect3D9Ex +#define uMod_IDirect3D9 uMod_IDirect3D9Ex +#define m_pIDirect3D9 m_pIDirect3D9Ex +#define PRE_MESSAGE "uMod_IDirect3D9Ex" + +#include "uMod_IDirect3D9.cpp" + + +HRESULT __stdcall uMod_IDirect3D9Ex::CreateDeviceEx( UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode, IDirect3DDevice9Ex **ppReturnedDeviceInterface) +{ + Message( "uMod_IDirect3D9Ex::CreateDeviceEx: %lu\n", this); + // we intercept this call and provide our own "fake" Device Object + HRESULT hres = m_pIDirect3D9Ex->CreateDeviceEx( Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, pFullscreenDisplayMode, ppReturnedDeviceInterface); + + int count = 1; + if (pPresentationParameters!=NULL) count = pPresentationParameters->BackBufferCount; + uMod_IDirect3DDevice9Ex *pIDirect3DDevice9Ex = new uMod_IDirect3DDevice9Ex(*ppReturnedDeviceInterface, uMod_Server, count); + + // store our pointer (the fake one) for returning it to the calling program + *ppReturnedDeviceInterface = pIDirect3DDevice9Ex; + + return(hres); + return (m_pIDirect3D9Ex->CreateDeviceEx( Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, pFullscreenDisplayMode, ppReturnedDeviceInterface)); +} + +HRESULT __stdcall uMod_IDirect3D9Ex::EnumAdapterModesEx( UINT Adapter, const D3DDISPLAYMODEFILTER *pFilter, UINT Mode, D3DDISPLAYMODEEX *pMode) +{ + return (m_pIDirect3D9Ex->EnumAdapterModesEx( Adapter, pFilter, Mode, pMode)); +} + +HRESULT __stdcall uMod_IDirect3D9Ex::GetAdapterDisplayModeEx( UINT Adapter, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) +{ + return (m_pIDirect3D9Ex->GetAdapterDisplayModeEx( Adapter, pMode, pRotation)); +} + +HRESULT __stdcall uMod_IDirect3D9Ex::GetAdapterLUID( UINT Adapter, LUID *pLUID) +{ + return (m_pIDirect3D9Ex->GetAdapterLUID( Adapter, pLUID)); +} + +UINT __stdcall uMod_IDirect3D9Ex::GetAdapterModeCountEx( UINT Adapter, const D3DDISPLAYMODEFILTER *pFilter) +{ + return (m_pIDirect3D9Ex->GetAdapterModeCountEx( Adapter, pFilter)); +} + diff --git a/uMod2/uMod_DX9/uMod_IDirect3D9Ex.h b/uMod2/uMod_DX9/uMod_IDirect3D9Ex.h new file mode 100644 index 0000000..aab671c --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3D9Ex.h @@ -0,0 +1,73 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + * + * BIG THANKS TO Michael Koch + * (proxydll_9.zip) + * + */ + + +#ifndef uMod_IDirect3D9Ex_H_ +#define uMod_IDirect3D9Ex_H_ + + +#include +#include +#include "uMod_TextureServer.h" +#include "uMod_TextureClient.h" + +class uMod_IDirect3D9Ex : public IDirect3D9Ex +{ +public: + uMod_IDirect3D9Ex( IDirect3D9Ex *pOriginal, uMod_TextureServer *server); + virtual ~uMod_IDirect3D9Ex(void); + + // The original DX9 function definitions + HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); + ULONG __stdcall AddRef(void); + ULONG __stdcall Release(void); + HRESULT __stdcall RegisterSoftwareDevice(void* pInitializeFunction); + UINT __stdcall GetAdapterCount(void); + HRESULT __stdcall GetAdapterIdentifier(UINT Adapter,DWORD Flags,D3DADAPTER_IDENTIFIER9* pIdentifier) ; + UINT __stdcall GetAdapterModeCount(UINT Adapter, D3DFORMAT Format); + HRESULT __stdcall EnumAdapterModes(UINT Adapter,D3DFORMAT Format,UINT Mode,D3DDISPLAYMODE* pMode) ; + HRESULT __stdcall GetAdapterDisplayMode( UINT Adapter,D3DDISPLAYMODE* pMode) ; + HRESULT __stdcall CheckDeviceType(UINT iAdapter,D3DDEVTYPE DevType,D3DFORMAT DisplayFormat,D3DFORMAT BackBufferFormat,BOOL bWindowed) ; + HRESULT __stdcall CheckDeviceFormat(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,DWORD Usage,D3DRESOURCETYPE RType,D3DFORMAT CheckFormat) ; + HRESULT __stdcall CheckDeviceMultiSampleType(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SurfaceFormat,BOOL Windowed,D3DMULTISAMPLE_TYPE MultiSampleType,DWORD* pQualityLevels) ; + HRESULT __stdcall CheckDepthStencilMatch(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,D3DFORMAT RenderTargetFormat,D3DFORMAT DepthStencilFormat) ; + HRESULT __stdcall CheckDeviceFormatConversion(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SourceFormat,D3DFORMAT TargetFormat); + HRESULT __stdcall GetDeviceCaps(UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps) ; + HMONITOR __stdcall GetAdapterMonitor(UINT Adapter) ; + HRESULT __stdcall CreateDevice(UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface) ; + + HRESULT __stdcall CreateDeviceEx( UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode, IDirect3DDevice9Ex **ppReturnedDeviceInterface); + HRESULT __stdcall EnumAdapterModesEx( UINT Adapter, const D3DDISPLAYMODEFILTER *pFilter, UINT Mode, D3DDISPLAYMODEEX *pMode); + HRESULT __stdcall GetAdapterDisplayModeEx( UINT Adapter, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation); + HRESULT __stdcall GetAdapterLUID( UINT Adapter, LUID *pLUID); + UINT __stdcall GetAdapterModeCountEx( UINT Adapter, const D3DDISPLAYMODEFILTER *pFilter); + + +private: + IDirect3D9Ex *m_pIDirect3D9Ex; + uMod_TextureServer* uMod_Server; +}; + +#endif diff --git a/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp b/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp new file mode 100644 index 0000000..169ff96 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.cpp @@ -0,0 +1,364 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + * some function (e.g. AddReff()) are presumed to work on the texture object which belong to them + * if this texture was switched, we must redirect this calls to the CrossRef_D3Dtex texture object + */ + + +#include "uMod_Main.h" + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::QueryInterface(REFIID riid, void** ppvObj) +{ + if (riid==IID_IDirect3D9) + { + // This function should never be called with IID_IDirect3D9 by the game + // thus this call comes from our own dll to ask for the texture type + // 0x01000000L == uMod_IDirect3DTexture9 + // 0x01000001L == uMod_IDirect3DVolumeTexture9 + // 0x01000002L == uMod_IDirect3DCubeTexture9 + + *ppvObj = this; + return (0x01000002L); + } + HRESULT hRes; + if (CrossRef_D3Dtex!=NULL) + { + hRes = CrossRef_D3Dtex->m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==CrossRef_D3Dtex->m_D3Dtex) *ppvObj=this; + } + else + { + hRes = m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==m_D3Dtex) *ppvObj=this; + } + return (hRes); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DCubeTexture9::AddRef() +{ + if (FAKE) return (1); //bug, this case should never happen + if (CrossRef_D3Dtex!=NULL) + { + return (CrossRef_D3Dtex->m_D3Dtex->AddRef()); + } + else return (m_D3Dtex->AddRef()); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DCubeTexture9::Release() +{ + Message("uMod_IDirect3DCubeTexture9::Release(): %lu\n", this); + + void *cpy; + long ret = m_D3Ddev->QueryInterface( IID_IDirect3DTexture9, &cpy); + + ULONG count; + if (FAKE) + { + UnswitchTextures( this); + count = m_D3Dtex->Release(); //count must be zero, cause we don't call AddRef of fake_textures + } + else + { + if (CrossRef_D3Dtex!=NULL) //if this texture is switched with a fake texture + { + uMod_IDirect3DCubeTexture9 *fake_texture = CrossRef_D3Dtex; + count = fake_texture->m_D3Dtex->Release(); //release the original texture + if (count==0) //if texture is released we switch the textures back + { + UnswitchTextures(this); + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetSingleCubeTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetSingleCubeTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + } + } + else + { + count = m_D3Dtex->Release(); + } + } + + if (count==0) //if this texture is released, we clean up + { + // if this texture is the LastCreatedTexture, the next time LastCreatedTexture would be added, + // the hash of a non existing texture would be calculated + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetLastCreatedCubeTexture()==this) ((uMod_IDirect3DDevice9*) m_D3Ddev)->SetLastCreatedCubeTexture( NULL); + else ((uMod_IDirect3DDevice9*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetLastCreatedCubeTexture()==this) ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->SetLastCreatedCubeTexture( NULL); + else ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + + delete(this); + } + return (count); +} + +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::GetDevice(IDirect3DDevice9** ppDevice) +{ + *ppDevice = m_D3Ddev; + return D3D_OK; +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); + return (m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); + return (m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::FreePrivateData(REFGUID refguid) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->FreePrivateData(refguid)); + return (m_D3Dtex->FreePrivateData(refguid)); +} + +DWORD APIENTRY uMod_IDirect3DCubeTexture9::SetPriority(DWORD PriorityNew) +{ + return (m_D3Dtex->SetPriority(PriorityNew)); +} + +DWORD APIENTRY uMod_IDirect3DCubeTexture9::GetPriority() +{ + return (m_D3Dtex->GetPriority()); +} + +void APIENTRY uMod_IDirect3DCubeTexture9::PreLoad() +{ + m_D3Dtex->PreLoad(); +} + +D3DRESOURCETYPE APIENTRY uMod_IDirect3DCubeTexture9::GetType() +{ + return (m_D3Dtex->GetType()); +} + +DWORD APIENTRY uMod_IDirect3DCubeTexture9::SetLOD(DWORD LODNew) +{ + return (m_D3Dtex->SetLOD(LODNew)); +} + +DWORD APIENTRY uMod_IDirect3DCubeTexture9::GetLOD() +{ + return (m_D3Dtex->GetLOD()); +} + +DWORD APIENTRY uMod_IDirect3DCubeTexture9::GetLevelCount() +{ + return (m_D3Dtex->GetLevelCount()); +} + +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::SetAutoGenFilterType(D3DTEXTUREFILTERTYPE FilterType) +{ + return (m_D3Dtex->SetAutoGenFilterType(FilterType)); +} + +D3DTEXTUREFILTERTYPE APIENTRY uMod_IDirect3DCubeTexture9::GetAutoGenFilterType() +{ + return (m_D3Dtex->GetAutoGenFilterType()); +} + +void APIENTRY uMod_IDirect3DCubeTexture9::GenerateMipSubLevels() +{ + m_D3Dtex->GenerateMipSubLevels(); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::AddDirtyRect(D3DCUBEMAP_FACES FaceType, CONST RECT* pDirtyRect) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->AddDirtyRect( FaceType, pDirtyRect)); + return (m_D3Dtex->AddDirtyRect( FaceType, pDirtyRect)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::GetLevelDesc(UINT Level,D3DSURFACE_DESC *pDesc) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetLevelDesc(Level, pDesc)); + return (m_D3Dtex->GetLevelDesc(Level, pDesc)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::GetCubeMapSurface(D3DCUBEMAP_FACES FaceType, UINT Level, IDirect3DSurface9 **ppCubeMapSurface) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetCubeMapSurface( FaceType, Level, ppCubeMapSurface)); + return (m_D3Dtex->GetCubeMapSurface( FaceType, Level, ppCubeMapSurface)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::LockRect( D3DCUBEMAP_FACES FaceType, UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->LockRect( FaceType, Level, pLockedRect, pRect, Flags)); + return (m_D3Dtex->LockRect( FaceType, Level, pLockedRect, pRect, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DCubeTexture9::UnlockRect( D3DCUBEMAP_FACES FaceType, UINT Level) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->UnlockRect( FaceType, Level)); + return (m_D3Dtex->UnlockRect( FaceType, Level)); +} + + + +int uMod_IDirect3DCubeTexture9::GetHash(MyTypeHash &hash) +{ + hash=0u; + if (FAKE) return (RETURN_BAD_ARGUMENT); + IDirect3DCubeTexture9 *pTexture = m_D3Dtex; + if (CrossRef_D3Dtex!=NULL) pTexture = CrossRef_D3Dtex->m_D3Dtex; + + //IDirect3DSurface9 *pOffscreenSurface = NULL; + //IDirect3DCubeTexture9 *pOffscreenTexture = NULL; + IDirect3DSurface9 *pResolvedSurface = NULL; + D3DLOCKED_RECT d3dlr; + D3DSURFACE_DESC desc; + + if (pTexture->GetLevelDesc(0, &desc)!=D3D_OK) //get the format and the size of the texture + { + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: GetLevelDesc \n"); + return (RETURN_GetLevelDesc_FAILED); + } + + Message("uMod_IDirect3DCubeTexture9::GetHash() (%d %d) %d\n", desc.Width, desc.Height, desc.Format); + +/* + if (desc.Pool==D3DPOOL_DEFAULT) //get the raw data of the texture + { + //Message("uMod_IDirect3DCubeTexture9::GetHash() (D3DPOOL_DEFAULT)\n"); + + IDirect3DSurface9 *pSurfaceLevel_orig = NULL; + if (pTexture->GetSurfaceLevel( 0, &pSurfaceLevel_orig)!=D3D_OK) + { + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: GetSurfaceLevel 1 (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + if (desc.MultiSampleType != D3DMULTISAMPLE_NONE) + { + //Message("uMod_IDirect3DCubeTexture9::GetHash() MultiSampleType\n"); + if (D3D_OK!=m_D3Ddev->CreateRenderTarget( desc.Width, desc.Height, desc.Format, D3DMULTISAMPLE_NONE, 0, FALSE, &pResolvedSurface, NULL )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: CreateRenderTarget (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + if (D3D_OK!=m_D3Ddev->StretchRect( pSurfaceLevel_orig, NULL, pResolvedSurface, NULL, D3DTEXF_NONE )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: StretchRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + pSurfaceLevel_orig = pResolvedSurface; + } + + + if (D3D_OK!=m_D3Ddev->CreateOffscreenPlainSurface( desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &pOffscreenSurface, NULL)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: CreateOffscreenPlainSurface (D3DPOOL_DEFAULT)\n"); + return (RETURN_TEXTURE_NOT_LOADED); + } + + if (D3D_OK!=m_D3Ddev->GetRenderTargetData( pSurfaceLevel_orig, pOffscreenSurface)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: GetRenderTargetData (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + pSurfaceLevel_orig->Release(); + + if (pOffscreenSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: LockRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + } + else + */ + if (pTexture->LockRect( D3DCUBEMAP_FACE_POSITIVE_X, 0, &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: LockRect 1\n"); + if (pTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_X, 0, &pResolvedSurface)!=D3D_OK) + { + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: GetSurfaceLevel\n"); + return (RETURN_LockRect_FAILED); + } + if (pResolvedSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + pResolvedSurface->Release(); + Message("uMod_IDirect3DCubeTexture9::GetHash() Failed: LockRect 2\n"); + return (RETURN_LockRect_FAILED); + } + } + + + int size = (GetBitsFromFormat( desc.Format) * desc.Width*desc.Height)/8; + + hash = GetCRC32( (char*) d3dlr.pBits, size); //calculate the crc32 of the texture +/* + if (pOffscreenSurface!=NULL) + { + pOffscreenSurface->UnlockRect(); + pOffscreenSurface->Release(); + //pOffscreenTexture->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + } + else + */ + if (pResolvedSurface!=NULL) + { + pResolvedSurface->UnlockRect(); + pResolvedSurface->Release(); + } + else + { + pTexture->UnlockRect( D3DCUBEMAP_FACE_POSITIVE_X, 0); //unlock the raw data + } + + Message("uMod_IDirect3DCubeTexture9::GetHash() %#lX (%d %d) %d = %d\n", hash, desc.Width, desc.Height, desc.Format, size); + return (RETURN_OK); +} + + diff --git a/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h b/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h new file mode 100644 index 0000000..67678a1 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DCubeTexture9.h @@ -0,0 +1,126 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +/* + * + * BIG THANKS TO Matthew L (Azorbix) + * (Direct3D StarterKit v3.0) + * + */ + + +#ifndef uMod_IDirect3DCubeTexture9_H +#define uMod_IDirect3DCubeTexture9_H + +#include +#include + +#include "uMod_Defines.h" + + + +interface uMod_IDirect3DCubeTexture9 : public IDirect3DCubeTexture9 +{ + uMod_IDirect3DCubeTexture9(IDirect3DCubeTexture9 **ppTex, IDirect3DDevice9 *pIDirect3DDevice9) + { + m_D3Dtex = *ppTex; //Texture which will be displayed and will be passed to the game + m_D3Ddev = pIDirect3DDevice9; //device pointer + CrossRef_D3Dtex = NULL; //cross reference + // fake texture: store the pointer to the original uMod_IDirect3DCubeTexture9 object, needed if a fake texture is unselected + // original texture: stores the pointer to the fake texture object, is needed if original texture is deleted, + // thus the fake texture can also be deleted + Reference = -1; //need for fast deleting + Hash = 0u; + FAKE = false; + } + + // callback interface + IDirect3DCubeTexture9 *m_D3Dtex; + uMod_IDirect3DCubeTexture9 *CrossRef_D3Dtex; + IDirect3DDevice9 *m_D3Ddev; + int Reference; + MyTypeHash Hash; + bool FAKE; + + // original interface + STDMETHOD(QueryInterface) (REFIID riid, void** ppvObj); + STDMETHOD_(ULONG,AddRef)(); + STDMETHOD_(ULONG,Release)(); + STDMETHOD(GetDevice)(IDirect3DDevice9** ppDevice); + STDMETHOD(SetPrivateData)(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags); + STDMETHOD(GetPrivateData)(REFGUID refguid,void* pData,DWORD* pSizeOfData); + STDMETHOD(FreePrivateData)(REFGUID refguid); + STDMETHOD_(DWORD, SetPriority)(DWORD PriorityNew); + STDMETHOD_(DWORD, GetPriority)(); + STDMETHOD_(void, PreLoad)(); + STDMETHOD_(D3DRESOURCETYPE, GetType)(); + STDMETHOD_(DWORD, SetLOD)(DWORD LODNew); + STDMETHOD_(DWORD, GetLOD)(); + STDMETHOD_(DWORD, GetLevelCount)(); + STDMETHOD(SetAutoGenFilterType)(D3DTEXTUREFILTERTYPE FilterType); + STDMETHOD_(D3DTEXTUREFILTERTYPE, GetAutoGenFilterType)(); + STDMETHOD_(void, GenerateMipSubLevels)(); + + STDMETHOD(AddDirtyRect)(D3DCUBEMAP_FACES FaceType, CONST RECT* pDirtyRect); + STDMETHOD(GetLevelDesc)(UINT Level, D3DSURFACE_DESC *pDesc); + STDMETHOD(GetCubeMapSurface)(D3DCUBEMAP_FACES FaceType, UINT Level, IDirect3DSurface9 **ppCubeMapSurface); + STDMETHOD(LockRect)( D3DCUBEMAP_FACES FaceType, UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags); + STDMETHOD(UnlockRect)(D3DCUBEMAP_FACES FaceType, UINT Level); + + + int GetHash(MyTypeHash &hash); +}; + + + +inline void UnswitchTextures(uMod_IDirect3DCubeTexture9 *pTexture) +{ + uMod_IDirect3DCubeTexture9* CrossRef = pTexture->CrossRef_D3Dtex; + if (CrossRef!=NULL) + { + // switch textures back + IDirect3DCubeTexture9* cpy = pTexture->m_D3Dtex; + pTexture->m_D3Dtex = CrossRef->m_D3Dtex; + CrossRef->m_D3Dtex = cpy; + + // cancel the link + CrossRef->CrossRef_D3Dtex = NULL; + pTexture->CrossRef_D3Dtex = NULL; + } +} + +inline int SwitchTextures( uMod_IDirect3DCubeTexture9 *pTexture1, uMod_IDirect3DCubeTexture9 *pTexture2) +{ + if (pTexture1->m_D3Ddev == pTexture2->m_D3Ddev && pTexture1->CrossRef_D3Dtex == NULL && pTexture2->CrossRef_D3Dtex == NULL) + { + // make cross reference + pTexture1->CrossRef_D3Dtex = pTexture2; + pTexture2->CrossRef_D3Dtex = pTexture1; + + // switch textures + IDirect3DCubeTexture9* cpy = pTexture2->m_D3Dtex; + pTexture2->m_D3Dtex = pTexture1->m_D3Dtex; + pTexture1->m_D3Dtex = cpy; + return (RETURN_OK); + } + else return (RETURN_TEXTURE_NOT_SWITCHED); +} + + +#endif diff --git a/uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp b/uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp new file mode 100644 index 0000000..9d04ca1 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DDevice9.cpp @@ -0,0 +1,1224 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + +#ifndef RETURN_QueryInterface +#define RETURN_QueryInterface 0x01000000L +#endif + +#ifndef PRE_MESSAGE +#define PRE_MESSAGE "uMod_IDirect3DDevice9" +#endif + + +int uMod_IDirect3DDevice9::CreateSingleTexture(void) +{ + if (SingleTexture!=NULL && SingleVolumeTexture!=NULL && SingleCubeTexture!=NULL && TextureColour==uMod_Client->TextureColour) return (RETURN_OK); + TextureColour = uMod_Client->TextureColour; + if (SingleTexture==NULL) //create texture + { + if( D3D_OK != CreateTexture(8, 8, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, (IDirect3DTexture9**) &SingleTexture, NULL)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): CreateTexture Failed\n"); + SingleTexture = NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + LastCreatedTexture = NULL; // set LastCreatedTexture to NULL, cause LastCreatedTexture is equal SingleTexture + SingleTexture->FAKE = true; //this is no texture created from by game + SingleTexture->Reference = -2; + } + + { + D3DLOCKED_RECT d3dlr; + IDirect3DTexture9 *pD3Dtex = SingleTexture->m_D3Dtex; + + if (D3D_OK!=pD3Dtex->LockRect(0, &d3dlr, 0, 0)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): LockRect Failed\n"); + SingleTexture->Release(); + SingleTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + DWORD *pDst = (DWORD*)d3dlr.pBits; + + for (int i=0; i<8*8; i++) pDst[i] = TextureColour; + pD3Dtex->UnlockRect(0); + } + + if (SingleVolumeTexture==NULL) //create texture + { + if( D3D_OK != CreateVolumeTexture(8, 8, 8, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, (IDirect3DVolumeTexture9**) &SingleVolumeTexture, NULL)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): CreateVolumeTexture Failed\n"); + SingleVolumeTexture = NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + LastCreatedVolumeTexture = NULL; // set LastCreatedTexture to NULL, cause LastCreatedTexture is equal SingleTexture + SingleVolumeTexture->FAKE = true; //this is no texture created from by game + SingleVolumeTexture->Reference = -2; + } + + { + D3DLOCKED_BOX d3dlr; + IDirect3DVolumeTexture9 *pD3Dtex = SingleVolumeTexture->m_D3Dtex; + //LockBox)(UINT Level, D3DLOCKED_BOX *pLockedVolume, CONST D3DBOX *pBox, + if (D3D_OK!=pD3Dtex->LockBox(0, &d3dlr, 0, 0)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): LockBox Failed\n"); + SingleVolumeTexture->Release(); + SingleVolumeTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + DWORD *pDst = (DWORD*)d3dlr.pBits; + + for (int i=0; i<8*8*8; i++) pDst[i] = TextureColour; + pD3Dtex->UnlockBox(0); + } + if (SingleCubeTexture==NULL) //create texture + { + if( D3D_OK != CreateCubeTexture(8, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, (IDirect3DCubeTexture9**) &SingleCubeTexture, NULL)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): CreateCubeTexture Failed\n"); + SingleCubeTexture = NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + LastCreatedCubeTexture = NULL; // set LastCreatedTexture to NULL, cause LastCreatedTexture is equal SingleTexture + SingleCubeTexture->FAKE = true; //this is no texture created from by game + SingleCubeTexture->Reference = -2; + } + + { + D3DLOCKED_RECT d3dlr; + IDirect3DCubeTexture9 *pD3Dtex = SingleCubeTexture->m_D3Dtex; + + for (int c=0; c<6; c++) + { + if (D3D_OK!=pD3Dtex->LockRect( (D3DCUBEMAP_FACES) c, 0, &d3dlr, 0, 0)) + { + Message( PRE_MESSAGE "::CreateSingleTexture(): LockRect (Cube) Failed\n"); + SingleCubeTexture->Release(); + SingleCubeTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + DWORD *pDst = (DWORD*)d3dlr.pBits; + + for (int i=0; i<8*8; i++) pDst[i] = TextureColour; + pD3Dtex->UnlockRect((D3DCUBEMAP_FACES)c, 0); + } + } + + return (RETURN_OK); +} + +uMod_IDirect3DDevice9::uMod_IDirect3DDevice9( IDirect3DDevice9* pOriginal, uMod_TextureServer* server, int back_buffer_count) +{ + Message( PRE_MESSAGE "::" PRE_MESSAGE "( %lu, %lu): %lu\n", pOriginal, server, this); + + BackBufferCount = back_buffer_count; + NormalRendering = true; + + uMod_Server = server; + uMod_Client = new uMod_TextureClient( uMod_Server, this); //get a new texture client for this device + + LastCreatedTexture = NULL; + LastCreatedVolumeTexture = NULL; + LastCreatedCubeTexture = NULL; + m_pIDirect3DDevice9 = pOriginal; // store the pointer to original object + TextureColour = D3DCOLOR_ARGB(255,0,255,0); + + CounterSaveSingleTexture = -20; + + SingleTextureMod = 0; + SingleTexture = NULL; + SingleVolumeTexture = NULL; + SingleCubeTexture = NULL; + OSD_Font = NULL; + uMod_Reference = 1; +} + +uMod_IDirect3DDevice9::~uMod_IDirect3DDevice9(void) +{ + Message( PRE_MESSAGE "::~" PRE_MESSAGE "(): %lu\n", this); +} + +HRESULT uMod_IDirect3DDevice9::QueryInterface(REFIID riid, void** ppvObj) +{ + // check if original dll can provide interface. then send *our* address + if (riid==IID_IDirect3DTexture9) + { + // This function should never be called with IDirect3DTexture9 by the game + *ppvObj = this; + return (RETURN_QueryInterface); + } + + *ppvObj = NULL; + Message( PRE_MESSAGE "::QueryInterface(): %lu\n", this); + HRESULT hRes = m_pIDirect3DDevice9->QueryInterface(riid, ppvObj); + + if (*ppvObj == m_pIDirect3DDevice9) + { + uMod_Reference++; //increasing our counter + *ppvObj = this; + } + + return (hRes); +} + +ULONG uMod_IDirect3DDevice9::AddRef(void) +{ + uMod_Reference++; //increasing our counter + Message("%lu = " PRE_MESSAGE "::AddRef(): %lu\n", uMod_Reference, this); + return (m_pIDirect3DDevice9->AddRef()); +} + +ULONG uMod_IDirect3DDevice9::Release(void) +{ + if (--uMod_Reference==0) //if our counter drops to zero, the real device will be deleted, so we clean up before + { + // we must not release the fake textures, cause they are released if the target textures are released + // and the target textures are released by the game. + + if (SingleTexture!=NULL) SingleTexture->Release(); //this is the only texture we must release by ourself + if (SingleVolumeTexture!=NULL) SingleVolumeTexture->Release(); //this is the only texture we must release by ourself + if (SingleCubeTexture!=NULL) SingleCubeTexture->Release(); //this is the only texture we must release by ourself + if (OSD_Font!=NULL) OSD_Font->Release(); + + if (uMod_Client!=NULL) delete uMod_Client; //must be deleted at the end, because other releases might call a function of this object + + uMod_Client = NULL; + SingleTexture = NULL; + OSD_Font = NULL; + } + + ULONG count = m_pIDirect3DDevice9->Release(); + Message("%lu = " PRE_MESSAGE "::Release(): %lu\n", count, this); + if (uMod_Reference!=count) //bug + { + Message("Error in " PRE_MESSAGE "::Release(): %lu!=%lu\n", uMod_Reference, count); + } + + if (count==0u) delete(this); + return (count); +} + +HRESULT uMod_IDirect3DDevice9::TestCooperativeLevel(void) +{ + return(m_pIDirect3DDevice9->TestCooperativeLevel()); +} + +UINT uMod_IDirect3DDevice9::GetAvailableTextureMem(void) +{ + return(m_pIDirect3DDevice9->GetAvailableTextureMem()); +} + +HRESULT uMod_IDirect3DDevice9::EvictManagedResources(void) +{ + return(m_pIDirect3DDevice9->EvictManagedResources()); +} + +HRESULT uMod_IDirect3DDevice9::GetDirect3D(IDirect3D9** ppD3D9) +{ + return(m_pIDirect3DDevice9->GetDirect3D(ppD3D9)); +} + +HRESULT uMod_IDirect3DDevice9::GetDeviceCaps(D3DCAPS9* pCaps) +{ + return(m_pIDirect3DDevice9->GetDeviceCaps(pCaps)); +} + +HRESULT uMod_IDirect3DDevice9::GetDisplayMode(UINT iSwapChain,D3DDISPLAYMODE* pMode) +{ + return(m_pIDirect3DDevice9->GetDisplayMode(iSwapChain, pMode)); +} + +HRESULT uMod_IDirect3DDevice9::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters) +{ + return(m_pIDirect3DDevice9->GetCreationParameters(pParameters)); +} + +HRESULT uMod_IDirect3DDevice9::SetCursorProperties(UINT XHotSpot,UINT YHotSpot,IDirect3DSurface9* pCursorBitmap) +{ + return(m_pIDirect3DDevice9->SetCursorProperties(XHotSpot,YHotSpot,pCursorBitmap)); +} + +void uMod_IDirect3DDevice9::SetCursorPosition(int X,int Y,DWORD Flags) +{ + m_pIDirect3DDevice9->SetCursorPosition(X,Y,Flags); +} + +BOOL uMod_IDirect3DDevice9::ShowCursor(BOOL bShow) +{ + return(m_pIDirect3DDevice9->ShowCursor(bShow)); +} + +HRESULT uMod_IDirect3DDevice9::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DSwapChain9** pSwapChain) +{ + return(m_pIDirect3DDevice9->CreateAdditionalSwapChain(pPresentationParameters,pSwapChain)); +} + +HRESULT uMod_IDirect3DDevice9::GetSwapChain(UINT iSwapChain,IDirect3DSwapChain9** pSwapChain) +{ + return(m_pIDirect3DDevice9->GetSwapChain(iSwapChain,pSwapChain)); +} + +UINT uMod_IDirect3DDevice9::GetNumberOfSwapChains(void) +{ + return(m_pIDirect3DDevice9->GetNumberOfSwapChains()); +} + +HRESULT uMod_IDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParameters) +{ + if(OSD_Font!=NULL) {OSD_Font->Release(); OSD_Font=NULL;} //the game will crashes if the font is not released before the game is minimized! + return(m_pIDirect3DDevice9->Reset(pPresentationParameters)); +} + +HRESULT uMod_IDirect3DDevice9::Present(CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion) +{ + return (m_pIDirect3DDevice9->Present( pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)); +} + +HRESULT uMod_IDirect3DDevice9::GetBackBuffer(UINT iSwapChain,UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer) +{ + return(m_pIDirect3DDevice9->GetBackBuffer(iSwapChain,iBackBuffer,Type,ppBackBuffer)); +} + +HRESULT uMod_IDirect3DDevice9::GetRasterStatus(UINT iSwapChain,D3DRASTER_STATUS* pRasterStatus) +{ + return(m_pIDirect3DDevice9->GetRasterStatus(iSwapChain,pRasterStatus)); +} + +HRESULT uMod_IDirect3DDevice9::SetDialogBoxMode(BOOL bEnableDialogs) +{ + return(m_pIDirect3DDevice9->SetDialogBoxMode(bEnableDialogs)); +} + +void uMod_IDirect3DDevice9::SetGammaRamp(UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp) +{ + (m_pIDirect3DDevice9->SetGammaRamp(iSwapChain,Flags,pRamp)); +} + +void uMod_IDirect3DDevice9::GetGammaRamp(UINT iSwapChain,D3DGAMMARAMP* pRamp) +{ + (m_pIDirect3DDevice9->GetGammaRamp(iSwapChain,pRamp)); +} + +HRESULT uMod_IDirect3DDevice9::CreateTexture(UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,HANDLE* pSharedHandle) +{ + //create real texture + //Message("uMod_IDirect3DDevice9::CreateTexture()\n"); + HRESULT ret = (m_pIDirect3DDevice9->CreateTexture(Width,Height,Levels,Usage,Format,Pool,ppTexture,pSharedHandle)); + if(ret != D3D_OK) return (ret); + + //create fake texture + uMod_IDirect3DTexture9 *texture = new uMod_IDirect3DTexture9( ppTexture, this); + if (texture) *ppTexture = texture; + + if (LastCreatedTexture!=NULL) //if a texture was loaded before, hopefully this texture contains now the data, so we can add it + { + if ( uMod_Client!=NULL) uMod_Client->AddTexture( LastCreatedTexture); + } + LastCreatedTexture = texture; + return (ret); +} + +HRESULT uMod_IDirect3DDevice9::CreateVolumeTexture(UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,HANDLE* pSharedHandle) +{ + //create real texture + //Message("uMod_IDirect3DDevice9::CreateVolumeTexture()\n"); + HRESULT ret = (m_pIDirect3DDevice9->CreateVolumeTexture(Width,Height,Depth, Levels,Usage,Format,Pool,ppVolumeTexture,pSharedHandle)); + if(ret != D3D_OK) return (ret); + + //create fake texture + uMod_IDirect3DVolumeTexture9 *texture = new uMod_IDirect3DVolumeTexture9( ppVolumeTexture, this); + if (texture) *ppVolumeTexture = texture; + + if (LastCreatedVolumeTexture!=NULL) //if a texture was loaded before, hopefully this texture contains now the data, so we can add it + { + if ( uMod_Client!=NULL) uMod_Client->AddTexture( LastCreatedVolumeTexture); + } + LastCreatedVolumeTexture = texture; + return (ret); +} + +HRESULT uMod_IDirect3DDevice9::CreateCubeTexture(UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,HANDLE* pSharedHandle) +{ + //create real texture + //Message("uMod_IDirect3DDevice9::CreateCubeTexture()\n"); + HRESULT ret = (m_pIDirect3DDevice9->CreateCubeTexture(EdgeLength, Levels,Usage,Format,Pool,ppCubeTexture,pSharedHandle)); + if(ret != D3D_OK) return (ret); + + //create fake texture + uMod_IDirect3DCubeTexture9 *texture = new uMod_IDirect3DCubeTexture9( ppCubeTexture, this); + if (texture) *ppCubeTexture = texture; + + if (LastCreatedCubeTexture!=NULL) //if a texture was loaded before, hopefully this texture contains now the data, so we can add it + { + if ( uMod_Client!=NULL) uMod_Client->AddTexture( LastCreatedCubeTexture); + } + LastCreatedCubeTexture = texture; + return (ret); +} + +HRESULT uMod_IDirect3DDevice9::CreateVertexBuffer(UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle) +{ + return(m_pIDirect3DDevice9->CreateVertexBuffer(Length,Usage,FVF,Pool,ppVertexBuffer,pSharedHandle)); +} + +HRESULT uMod_IDirect3DDevice9::CreateIndexBuffer(UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,HANDLE* pSharedHandle) +{ + return(m_pIDirect3DDevice9->CreateIndexBuffer(Length,Usage,Format,Pool,ppIndexBuffer,pSharedHandle)); +} + +HRESULT uMod_IDirect3DDevice9::CreateRenderTarget(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) +{ + return(m_pIDirect3DDevice9->CreateRenderTarget(Width,Height,Format,MultiSample,MultisampleQuality,Lockable,ppSurface,pSharedHandle)); +} + +HRESULT uMod_IDirect3DDevice9::CreateDepthStencilSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) +{ + return(m_pIDirect3DDevice9->CreateDepthStencilSurface(Width,Height,Format,MultiSample,MultisampleQuality,Discard,ppSurface,pSharedHandle)); +} + +HRESULT uMod_IDirect3DDevice9::UpdateSurface(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestinationSurface,CONST POINT* pDestPoint) +{ + return(m_pIDirect3DDevice9->UpdateSurface(pSourceSurface,pSourceRect,pDestinationSurface,pDestPoint)); +} + +HRESULT uMod_IDirect3DDevice9::UpdateTexture(IDirect3DBaseTexture9* pSourceTexture,IDirect3DBaseTexture9* pDestinationTexture) +{ + Message( PRE_MESSAGE "::UpdateTexture( %lu, %lu): %lu\n", pSourceTexture, pDestinationTexture, this); + // we must pass the real texture objects + + + uMod_IDirect3DTexture9* pSource = NULL; + uMod_IDirect3DVolumeTexture9* pSourceVolume = NULL; + uMod_IDirect3DCubeTexture9* pSourceCube = NULL; + IDirect3DBaseTexture9* cpy; + if( pSourceTexture != NULL ) + { + long int ret = pSourceTexture->QueryInterface( IID_IDirect3D9, (void**) &cpy); + switch (ret) + { + case 0x01000000L: + { + MyTypeHash hash; + pSource = (uMod_IDirect3DTexture9*)(pSourceTexture); + if (pSource->GetHash( hash) == RETURN_OK) + { + if (hash != pSource->Hash) // this hash has changed !! + { + pSource->Hash = hash; + if (pSource->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSource); + uMod_Client->LookUpToMod( pSource); + } + } + else if (pSource->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSource); // we better unswitch + + // the source must be the original texture if not switched and the fake texture if it is switched + if (pSource->CrossRef_D3Dtex!=NULL) pSourceTexture = pSource->CrossRef_D3Dtex->m_D3Dtex; + else pSourceTexture = pSource->m_D3Dtex; + break; + } + case 0x01000001L: + { + MyTypeHash hash; + pSourceVolume = (uMod_IDirect3DVolumeTexture9*)(pSourceTexture); + if (pSourceVolume->GetHash( hash) == RETURN_OK) + { + if (hash != pSourceVolume->Hash) // this hash has changed !! + { + pSourceVolume->Hash = hash; + if (pSourceVolume->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSourceVolume); + uMod_Client->LookUpToMod( pSourceVolume); + } + } + else if (pSourceVolume->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSourceVolume); // we better unswitch + + // the source must be the original texture if not switched and the fake texture if it is switched + if (pSourceVolume->CrossRef_D3Dtex!=NULL) pSourceTexture = pSourceVolume->CrossRef_D3Dtex->m_D3Dtex; + else pSourceTexture = pSourceVolume->m_D3Dtex; + break; + } + case 0x01000002L: + { + MyTypeHash hash; + pSourceCube = (uMod_IDirect3DCubeTexture9*)(pSourceTexture); + if (pSourceCube->GetHash( hash) == RETURN_OK) + { + if (hash != pSourceCube->Hash) // this hash has changed !! + { + pSourceCube->Hash = hash; + if (pSourceCube->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSourceCube); + uMod_Client->LookUpToMod( pSourceCube); + } + } + else if (pSourceCube->CrossRef_D3Dtex!=NULL) UnswitchTextures(pSourceCube); // we better unswitch + + // the source must be the original texture if not switched and the fake texture if it is switched + if (pSourceCube->CrossRef_D3Dtex!=NULL) pSourceTexture = pSourceCube->CrossRef_D3Dtex->m_D3Dtex; + else pSourceTexture = pSourceCube->m_D3Dtex; + break; + } + default: + break; // this is no fake texture and QueryInterface failed, because IDirect3DBaseTexture9 object cannot be a IDirect3D9 object ;) + } + } + + + if (pDestinationTexture != NULL) + { + long int ret = pSourceTexture->QueryInterface( IID_IDirect3D9, (void**) &cpy); + switch (ret) + { + case 0x01000000L: + { + uMod_IDirect3DTexture9* pDest = (uMod_IDirect3DTexture9*)(pDestinationTexture); + + if (pSource!=NULL && pDest->Hash!=pSource->Hash) + { + pDest->Hash = pSource->Hash; // take over the hash + UnswitchTextures(pDest); + if (pSource->CrossRef_D3Dtex!=NULL) + { + uMod_IDirect3DTexture9 *cpy = pSource->CrossRef_D3Dtex; + UnswitchTextures(pSource); + SwitchTextures( cpy, pDest); + } + } + if (pDest->CrossRef_D3Dtex!=NULL) pDestinationTexture = pDest->CrossRef_D3Dtex->m_D3Dtex; // make sure to copy into the original texture + else pDestinationTexture = pDest->m_D3Dtex; + break; + } + case 0x01000001L: + { + uMod_IDirect3DVolumeTexture9* pDest = (uMod_IDirect3DVolumeTexture9*)(pDestinationTexture); + + if (pSourceVolume!=NULL && pDest->Hash!=pSourceVolume->Hash) + { + pDest->Hash = pSourceVolume->Hash; // take over the hash + UnswitchTextures(pDest); + if (pSourceVolume->CrossRef_D3Dtex!=NULL) + { + uMod_IDirect3DVolumeTexture9 *cpy = pSourceVolume->CrossRef_D3Dtex; + UnswitchTextures(pSourceVolume); + SwitchTextures( cpy, pDest); + } + } + if (pDest->CrossRef_D3Dtex!=NULL) pDestinationTexture = pDest->CrossRef_D3Dtex->m_D3Dtex; // make sure to copy into the original texture + else pDestinationTexture = pDest->m_D3Dtex; + break; + } + case 0x01000002L: + { + uMod_IDirect3DCubeTexture9* pDest = (uMod_IDirect3DCubeTexture9*)(pDestinationTexture); + + if (pSourceCube!=NULL && pDest->Hash!=pSourceCube->Hash) + { + pDest->Hash = pSourceCube->Hash; // take over the hash + UnswitchTextures(pDest); + if (pSourceCube->CrossRef_D3Dtex!=NULL) + { + uMod_IDirect3DCubeTexture9 *cpy = pSourceCube->CrossRef_D3Dtex; + UnswitchTextures(pSourceCube); + SwitchTextures( cpy, pDest); + } + } + if (pDest->CrossRef_D3Dtex!=NULL) pDestinationTexture = pDest->CrossRef_D3Dtex->m_D3Dtex; // make sure to copy into the original texture + else pDestinationTexture = pDest->m_D3Dtex; + break; + } + } + } + return(m_pIDirect3DDevice9->UpdateTexture(pSourceTexture,pDestinationTexture)); +} + +HRESULT uMod_IDirect3DDevice9::GetRenderTargetData(IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface) +{ + return(m_pIDirect3DDevice9->GetRenderTargetData(pRenderTarget,pDestSurface)); +} + +HRESULT uMod_IDirect3DDevice9::GetFrontBufferData(UINT iSwapChain,IDirect3DSurface9* pDestSurface) +{ + return(m_pIDirect3DDevice9->GetFrontBufferData(iSwapChain,pDestSurface)); +} + +HRESULT uMod_IDirect3DDevice9::StretchRect(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter) +{ + return(m_pIDirect3DDevice9->StretchRect(pSourceSurface,pSourceRect,pDestSurface,pDestRect,Filter)); +} + +HRESULT uMod_IDirect3DDevice9::ColorFill(IDirect3DSurface9* pSurface,CONST RECT* pRect,D3DCOLOR color) +{ + return(m_pIDirect3DDevice9->ColorFill(pSurface,pRect,color)); +} + +HRESULT uMod_IDirect3DDevice9::CreateOffscreenPlainSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) +{ + return(m_pIDirect3DDevice9->CreateOffscreenPlainSurface(Width,Height,Format,Pool,ppSurface,pSharedHandle)); +} + +HRESULT uMod_IDirect3DDevice9::SetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget) +{ + { + IDirect3DSurface9 *back_buffer; + NormalRendering = false; + for (int i=0; !NormalRendering && iGetBackBuffer( 0, i, D3DBACKBUFFER_TYPE_MONO, &back_buffer); + if (back_buffer == pRenderTarget) NormalRendering = true; + back_buffer->Release(); + } + } + return (m_pIDirect3DDevice9->SetRenderTarget(RenderTargetIndex,pRenderTarget)); +} + +HRESULT uMod_IDirect3DDevice9::GetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget) +{ + return (m_pIDirect3DDevice9->GetRenderTarget(RenderTargetIndex,ppRenderTarget)); +} + +HRESULT uMod_IDirect3DDevice9::SetDepthStencilSurface(IDirect3DSurface9* pNewZStencil) +{ + return(m_pIDirect3DDevice9->SetDepthStencilSurface(pNewZStencil)); +} + +HRESULT uMod_IDirect3DDevice9::GetDepthStencilSurface(IDirect3DSurface9** ppZStencilSurface) +{ + return(m_pIDirect3DDevice9->GetDepthStencilSurface(ppZStencilSurface)); +} + +HRESULT uMod_IDirect3DDevice9::BeginScene(void) +{ + //if ( NormalRendering ) + { + if (LastCreatedTexture!=NULL) // add the last created texture + { + uMod_Client->AddTexture( LastCreatedTexture); + } + if (LastCreatedVolumeTexture!=NULL) // add the last created texture + { + uMod_Client->AddTexture( LastCreatedVolumeTexture); + } + if (LastCreatedCubeTexture!=NULL) // add the last created texture + { + uMod_Client->AddTexture( LastCreatedCubeTexture); + } + uMod_Client->MergeUpdate(); // merge an update, if present + + if (uMod_Client->Bool_CheckAgainNonAdded) uMod_Client->CheckAgainNonAdded(); + + if (uMod_Client->BoolSaveSingleTexture) + { + if (CreateSingleTexture()==0) + { + if (uMod_Client->KeyBack>0 && (GetAsyncKeyState( uMod_Client->KeyBack ) &1) ) //ask for the status of the back key + { + UnswitchTextures( SingleTexture); // can be called, even if texture is not switched + UnswitchTextures( SingleVolumeTexture); // can be called, even if texture is not switched + UnswitchTextures( SingleCubeTexture); // can be called, even if texture is not switched + + if (CounterSaveSingleTexture<-10) {CounterSaveSingleTexture = 0; SingleTextureMod=0;} //first initialization of the counter + else if (--CounterSaveSingleTexture<0) + { + if (--SingleTextureMod<0) SingleTextureMod=2; + switch (SingleTextureMod) + { + case 0: + CounterSaveSingleTexture = uMod_Client->OriginalTextures.GetNumber() - 1; + break; + case 1: + CounterSaveSingleTexture = uMod_Client->OriginalVolumeTextures.GetNumber() - 1; + break; + case 2: + CounterSaveSingleTexture = uMod_Client->OriginalCubeTextures.GetNumber() - 1; + break; + } + } + + if (CounterSaveSingleTexture >= 0) + { + switch (SingleTextureMod) + { + case 0: + SwitchTextures( SingleTexture, uMod_Client->OriginalTextures[CounterSaveSingleTexture]); + SingleTexture->Hash = uMod_Client->OriginalTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + case 1: + SwitchTextures( SingleVolumeTexture, uMod_Client->OriginalVolumeTextures[CounterSaveSingleTexture]); + SingleVolumeTexture->Hash = uMod_Client->OriginalVolumeTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + case 2: + SwitchTextures( SingleCubeTexture, uMod_Client->OriginalCubeTextures[CounterSaveSingleTexture]); + SingleCubeTexture->Hash = uMod_Client->OriginalCubeTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + } + } + } + + if (uMod_Client->KeySave>0 && (GetAsyncKeyState( uMod_Client->KeySave ) &1) ) //ask for the status of the save key + { + switch (SingleTextureMod) + { + case 0: + uMod_Client->SaveTexture( SingleTexture); //after switching the SingleTexture holds the pointer to the original texture object + break; + case 1: + uMod_Client->SaveTexture( SingleVolumeTexture); //after switching the SingleTexture holds the pointer to the original texture object + break; + case 2: + uMod_Client->SaveTexture( SingleCubeTexture); //after switching the SingleTexture holds the pointer to the original texture object + break; + } + } + + if (uMod_Client->KeyNext>0 && (GetAsyncKeyState( uMod_Client->KeyNext ) &1) ) //ask for the status of the next key + { + UnswitchTextures( SingleTexture); // can be called, even if texture is not switched + UnswitchTextures( SingleVolumeTexture); // can be called, even if texture is not switched + UnswitchTextures( SingleCubeTexture); // can be called, even if texture is not switched + + if (CounterSaveSingleTexture<-10) {CounterSaveSingleTexture = 0; SingleTextureMod=0;} //first initialization of the counter + else + { + int num = 0; + switch (SingleTextureMod) + { + case 0: + num = uMod_Client->OriginalTextures.GetNumber(); + break; + case 1: + num = uMod_Client->OriginalVolumeTextures.GetNumber(); + break; + case 2: + num = uMod_Client->OriginalCubeTextures.GetNumber(); + break; + } + if (++CounterSaveSingleTexture>=num) + { + if (++SingleTextureMod>2) SingleTextureMod=0; + switch (SingleTextureMod) + { + case 0: + CounterSaveSingleTexture = uMod_Client->OriginalTextures.GetNumber()>0 ? 0 : - 1; + break; + case 1: + CounterSaveSingleTexture = uMod_Client->OriginalVolumeTextures.GetNumber()>0 ? 0 : - 1; + break; + case 2: + CounterSaveSingleTexture = uMod_Client->OriginalCubeTextures.GetNumber()>0 ? 0 : - 1; + break; + } + } + } + + if (CounterSaveSingleTexture >= 0) + { + switch (SingleTextureMod) + { + case 0: + SwitchTextures( SingleTexture, uMod_Client->OriginalTextures[CounterSaveSingleTexture]); + SingleTexture->Hash = uMod_Client->OriginalTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + case 1: + SwitchTextures( SingleVolumeTexture, uMod_Client->OriginalVolumeTextures[CounterSaveSingleTexture]); + SingleVolumeTexture->Hash = uMod_Client->OriginalVolumeTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + case 2: + SwitchTextures( SingleCubeTexture, uMod_Client->OriginalCubeTextures[CounterSaveSingleTexture]); + SingleCubeTexture->Hash = uMod_Client->OriginalCubeTextures[CounterSaveSingleTexture]->Hash; //set the hash for the display + break; + } + } + } + } + } + } + + return (m_pIDirect3DDevice9->BeginScene()); +} + +HRESULT uMod_IDirect3DDevice9::EndScene(void) +{ + if ( NormalRendering && uMod_Client->BoolSaveSingleTexture && SingleTexture!=NULL && SingleVolumeTexture!=NULL && SingleCubeTexture!=NULL) + { + if (OSD_Font==NULL) // create the font + { + if (D3D_OK!=D3DXCreateFontA( m_pIDirect3DDevice9, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &OSD_Font)) + { + OSD_Font=NULL; + return(m_pIDirect3DDevice9->EndScene()); + } + } + + char buffer[100]; + buffer[0]=0; + switch (SingleTextureMod) + { + case 0: + { + if (SingleTexture->CrossRef_D3Dtex!=NULL) sprintf_s( buffer, 100, "normal texture: %4d (1..%d): %#lX", CounterSaveSingleTexture+1, uMod_Client->OriginalTextures.GetNumber(), SingleTexture->Hash); + else + { + if (uMod_Client->OriginalTextures.GetNumber()>0) sprintf_s( buffer, 100, "normal texture: nothing selected (1..%d)", uMod_Client->OriginalTextures.GetNumber()); + else sprintf_s( buffer, 100, "normal texture: nothing loaded"); + } + break; + } + case 1: + { + if (SingleVolumeTexture->CrossRef_D3Dtex!=NULL) sprintf_s( buffer, 100, "volume texture: %4d (1..%d): %#lX", CounterSaveSingleTexture+1, uMod_Client->OriginalVolumeTextures.GetNumber(), SingleVolumeTexture->Hash); + else + { + if (uMod_Client->OriginalVolumeTextures.GetNumber()>0) sprintf_s( buffer, 100, "volume texture: nothing selected (1..%d)", uMod_Client->OriginalVolumeTextures.GetNumber()); + else sprintf_s( buffer, 100, "volume texture: nothing loaded"); + } + break; + } + case 2: + { + if (SingleCubeTexture->CrossRef_D3Dtex!=NULL) sprintf_s( buffer, 100, "cube texture: %4d (1..%d): %#lX", CounterSaveSingleTexture+1, uMod_Client->OriginalCubeTextures.GetNumber(), SingleCubeTexture->Hash); + else + { + if (uMod_Client->OriginalCubeTextures.GetNumber()>0) sprintf_s( buffer, 100, "cube texture: nothing selected (1..%d)", uMod_Client->OriginalCubeTextures.GetNumber()); + else sprintf_s( buffer, 100, "cube texture: nothing loaded"); + } + break; + } + } + D3DVIEWPORT9 viewport; + GetViewport( &viewport); + RECT rct; + rct.left=viewport.X + 10; + rct.right=0; //size of box is calculated automatically (DT_NOCLIP) + rct.top=viewport.Y + 10; + rct.bottom=0; //size of box is calculated automatically (DT_NOCLIP) + OSD_Font->DrawTextA(NULL, buffer, -1, &rct, DT_NOCLIP, uMod_Client->FontColour); + } + return(m_pIDirect3DDevice9->EndScene()); +} + +HRESULT uMod_IDirect3DDevice9::Clear(DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil) +{ + return(m_pIDirect3DDevice9->Clear(Count,pRects,Flags,Color,Z,Stencil)); +} + +HRESULT uMod_IDirect3DDevice9::SetTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix) +{ + return(m_pIDirect3DDevice9->SetTransform(State,pMatrix)); +} + +HRESULT uMod_IDirect3DDevice9::GetTransform(D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix) +{ + return(m_pIDirect3DDevice9->GetTransform(State,pMatrix)); +} + +HRESULT uMod_IDirect3DDevice9::MultiplyTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix) +{ + return(m_pIDirect3DDevice9->MultiplyTransform(State,pMatrix)); +} + +HRESULT uMod_IDirect3DDevice9::SetViewport(CONST D3DVIEWPORT9* pViewport) +{ + return(m_pIDirect3DDevice9->SetViewport(pViewport)); +} + +HRESULT uMod_IDirect3DDevice9::GetViewport(D3DVIEWPORT9* pViewport) +{ + return(m_pIDirect3DDevice9->GetViewport(pViewport)); +} + +HRESULT uMod_IDirect3DDevice9::SetMaterial(CONST D3DMATERIAL9* pMaterial) +{ + return(m_pIDirect3DDevice9->SetMaterial(pMaterial)); +} + +HRESULT uMod_IDirect3DDevice9::GetMaterial(D3DMATERIAL9* pMaterial) +{ + return(m_pIDirect3DDevice9->GetMaterial(pMaterial)); +} + +HRESULT uMod_IDirect3DDevice9::SetLight(DWORD Index,CONST D3DLIGHT9* pLight) +{ + return(m_pIDirect3DDevice9->SetLight(Index,pLight)); +} + +HRESULT uMod_IDirect3DDevice9::GetLight(DWORD Index,D3DLIGHT9* pLight) +{ + return(m_pIDirect3DDevice9->GetLight(Index,pLight)); +} + +HRESULT uMod_IDirect3DDevice9::LightEnable(DWORD Index,BOOL Enable) +{ + return(m_pIDirect3DDevice9->LightEnable(Index,Enable)); +} + +HRESULT uMod_IDirect3DDevice9::GetLightEnable(DWORD Index,BOOL* pEnable) +{ + return(m_pIDirect3DDevice9->GetLightEnable(Index, pEnable)); +} + +HRESULT uMod_IDirect3DDevice9::SetClipPlane(DWORD Index,CONST float* pPlane) +{ + return(m_pIDirect3DDevice9->SetClipPlane(Index, pPlane)); +} + +HRESULT uMod_IDirect3DDevice9::GetClipPlane(DWORD Index,float* pPlane) +{ + return(m_pIDirect3DDevice9->GetClipPlane(Index,pPlane)); +} + +HRESULT uMod_IDirect3DDevice9::SetRenderState(D3DRENDERSTATETYPE State,DWORD Value) +{ + return(m_pIDirect3DDevice9->SetRenderState(State, Value)); +} + +HRESULT uMod_IDirect3DDevice9::GetRenderState(D3DRENDERSTATETYPE State,DWORD* pValue) +{ + return(m_pIDirect3DDevice9->GetRenderState(State, pValue)); +} + +HRESULT uMod_IDirect3DDevice9::CreateStateBlock(D3DSTATEBLOCKTYPE Type,IDirect3DStateBlock9** ppSB) +{ + return(m_pIDirect3DDevice9->CreateStateBlock(Type,ppSB)); +} + +HRESULT uMod_IDirect3DDevice9::BeginStateBlock(void) +{ + return(m_pIDirect3DDevice9->BeginStateBlock()); +} + +HRESULT uMod_IDirect3DDevice9::EndStateBlock(IDirect3DStateBlock9** ppSB) +{ + return(m_pIDirect3DDevice9->EndStateBlock(ppSB)); +} + +HRESULT uMod_IDirect3DDevice9::SetClipStatus(CONST D3DCLIPSTATUS9* pClipStatus) +{ + return(m_pIDirect3DDevice9->SetClipStatus(pClipStatus)); +} + +HRESULT uMod_IDirect3DDevice9::GetClipStatus(D3DCLIPSTATUS9* pClipStatus) +{ + return(m_pIDirect3DDevice9->GetClipStatus( pClipStatus)); +} + +HRESULT uMod_IDirect3DDevice9::GetTexture(DWORD Stage,IDirect3DBaseTexture9** ppTexture) +{ + return(m_pIDirect3DDevice9->GetTexture(Stage,ppTexture)); +} + +HRESULT uMod_IDirect3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9* pTexture) +{ + // we must pass the real texture objects + // if (dev != this) this texture was not initialized through our device and is thus no fake texture object + + //IDirect3DDevice9 *dev = NULL; + IDirect3DBaseTexture9* cpy; + if( pTexture != NULL ) + { + long int ret = pTexture->QueryInterface( IID_IDirect3D9, (void**) &cpy); + switch (ret) + { + case 0x01000000L: + pTexture = ((uMod_IDirect3DTexture9*)(pTexture))->m_D3Dtex; break; + case 0x01000001L: + pTexture = ((uMod_IDirect3DVolumeTexture9*)(pTexture))->m_D3Dtex; break; + case 0x01000002L: + pTexture = ((uMod_IDirect3DCubeTexture9*)(pTexture))->m_D3Dtex; break; + default: + break; // this is no fake texture and QueryInterface failed, because IDirect3DBaseTexture9 object cannot be a IDirect3D9 object ;) + } + } + /* + if (pTexture != NULL && ((uMod_IDirect3DTexture9*)(pTexture))->GetDevice(&dev) == D3D_OK) + { + if(dev == this) pTexture = ((uMod_IDirect3DTexture9*)(pTexture))->m_D3Dtex; + } + */ + return (m_pIDirect3DDevice9->SetTexture(Stage, pTexture)); +} + +HRESULT uMod_IDirect3DDevice9::GetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue) +{ + return(m_pIDirect3DDevice9->GetTextureStageState(Stage,Type, pValue)); +} + +HRESULT uMod_IDirect3DDevice9::SetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value) +{ + return(m_pIDirect3DDevice9->SetTextureStageState(Stage,Type,Value)); +} + +HRESULT uMod_IDirect3DDevice9::GetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD* pValue) +{ + return(m_pIDirect3DDevice9->GetSamplerState(Sampler,Type, pValue)); +} + +HRESULT uMod_IDirect3DDevice9::SetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value) +{ + return(m_pIDirect3DDevice9->SetSamplerState(Sampler,Type,Value)); +} + +HRESULT uMod_IDirect3DDevice9::ValidateDevice(DWORD* pNumPasses) +{ + return(m_pIDirect3DDevice9->ValidateDevice( pNumPasses)); +} + +HRESULT uMod_IDirect3DDevice9::SetPaletteEntries(UINT PaletteNumber,CONST PALETTEENTRY* pEntries) +{ + return(m_pIDirect3DDevice9->SetPaletteEntries(PaletteNumber, pEntries)); +} + +HRESULT uMod_IDirect3DDevice9::GetPaletteEntries(UINT PaletteNumber,PALETTEENTRY* pEntries) +{ + return(m_pIDirect3DDevice9->GetPaletteEntries(PaletteNumber, pEntries)); +} + +HRESULT uMod_IDirect3DDevice9::SetCurrentTexturePalette(UINT PaletteNumber) +{ + return(m_pIDirect3DDevice9->SetCurrentTexturePalette(PaletteNumber)); +} + +HRESULT uMod_IDirect3DDevice9::GetCurrentTexturePalette(UINT *PaletteNumber) +{ + return(m_pIDirect3DDevice9->GetCurrentTexturePalette(PaletteNumber)); +} + +HRESULT uMod_IDirect3DDevice9::SetScissorRect(CONST RECT* pRect) +{ + return(m_pIDirect3DDevice9->SetScissorRect( pRect)); +} + +HRESULT uMod_IDirect3DDevice9::GetScissorRect( RECT* pRect) +{ + return(m_pIDirect3DDevice9->GetScissorRect( pRect)); +} + +HRESULT uMod_IDirect3DDevice9::SetSoftwareVertexProcessing(BOOL bSoftware) +{ + return(m_pIDirect3DDevice9->SetSoftwareVertexProcessing(bSoftware)); +} + +BOOL uMod_IDirect3DDevice9::GetSoftwareVertexProcessing(void) +{ + return(m_pIDirect3DDevice9->GetSoftwareVertexProcessing()); +} + +HRESULT uMod_IDirect3DDevice9::SetNPatchMode(float nSegments) +{ + return(m_pIDirect3DDevice9->SetNPatchMode(nSegments)); +} + +float uMod_IDirect3DDevice9::GetNPatchMode(void) +{ + return(m_pIDirect3DDevice9->GetNPatchMode()); +} + +HRESULT uMod_IDirect3DDevice9::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount) +{ + return(m_pIDirect3DDevice9->DrawPrimitive(PrimitiveType,StartVertex,PrimitiveCount)); +} + +HRESULT uMod_IDirect3DDevice9::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount) +{ + return(m_pIDirect3DDevice9->DrawIndexedPrimitive(PrimitiveType,BaseVertexIndex,MinVertexIndex,NumVertices,startIndex,primCount)); +} + +HRESULT uMod_IDirect3DDevice9::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) +{ + return(m_pIDirect3DDevice9->DrawPrimitiveUP(PrimitiveType,PrimitiveCount,pVertexStreamZeroData,VertexStreamZeroStride)); +} + +HRESULT uMod_IDirect3DDevice9::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) +{ + return(m_pIDirect3DDevice9->DrawIndexedPrimitiveUP(PrimitiveType,MinVertexIndex,NumVertices,PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData,VertexStreamZeroStride)); +} + +HRESULT uMod_IDirect3DDevice9::ProcessVertices(UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer9* pDestBuffer,IDirect3DVertexDeclaration9* pVertexDecl,DWORD Flags) +{ + return(m_pIDirect3DDevice9->ProcessVertices( SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags)); +} + +HRESULT uMod_IDirect3DDevice9::CreateVertexDeclaration(CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl) +{ + return(m_pIDirect3DDevice9->CreateVertexDeclaration( pVertexElements,ppDecl)); +} + +HRESULT uMod_IDirect3DDevice9::SetVertexDeclaration(IDirect3DVertexDeclaration9* pDecl) +{ + return(m_pIDirect3DDevice9->SetVertexDeclaration(pDecl)); +} + +HRESULT uMod_IDirect3DDevice9::GetVertexDeclaration(IDirect3DVertexDeclaration9** ppDecl) +{ + return(m_pIDirect3DDevice9->GetVertexDeclaration(ppDecl)); +} + +HRESULT uMod_IDirect3DDevice9::SetFVF(DWORD FVF) +{ + return(m_pIDirect3DDevice9->SetFVF(FVF)); +} + +HRESULT uMod_IDirect3DDevice9::GetFVF(DWORD* pFVF) +{ + return(m_pIDirect3DDevice9->GetFVF(pFVF)); +} + +HRESULT uMod_IDirect3DDevice9::CreateVertexShader(CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader) +{ + return(m_pIDirect3DDevice9->CreateVertexShader(pFunction,ppShader)); +} + +HRESULT uMod_IDirect3DDevice9::SetVertexShader(IDirect3DVertexShader9* pShader) +{ + return(m_pIDirect3DDevice9->SetVertexShader(pShader)); +} + +HRESULT uMod_IDirect3DDevice9::GetVertexShader(IDirect3DVertexShader9** ppShader) +{ + return(m_pIDirect3DDevice9->GetVertexShader(ppShader)); +} + +HRESULT uMod_IDirect3DDevice9::SetVertexShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) +{ + return(m_pIDirect3DDevice9->SetVertexShaderConstantF(StartRegister,pConstantData, Vector4fCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetVertexShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount) +{ + return(m_pIDirect3DDevice9->GetVertexShaderConstantF(StartRegister,pConstantData,Vector4fCount)); +} + +HRESULT uMod_IDirect3DDevice9::SetVertexShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) +{ + return(m_pIDirect3DDevice9->SetVertexShaderConstantI(StartRegister,pConstantData,Vector4iCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetVertexShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount) +{ + return(m_pIDirect3DDevice9->GetVertexShaderConstantI(StartRegister,pConstantData,Vector4iCount)); +} + +HRESULT uMod_IDirect3DDevice9::SetVertexShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) +{ + return(m_pIDirect3DDevice9->SetVertexShaderConstantB(StartRegister,pConstantData,BoolCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetVertexShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount) +{ + return(m_pIDirect3DDevice9->GetVertexShaderConstantB(StartRegister,pConstantData,BoolCount)); +} + +HRESULT uMod_IDirect3DDevice9::SetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride) +{ + return(m_pIDirect3DDevice9->SetStreamSource(StreamNumber,pStreamData,OffsetInBytes,Stride)); +} + +HRESULT uMod_IDirect3DDevice9::GetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9** ppStreamData,UINT* OffsetInBytes,UINT* pStride) +{ + return(m_pIDirect3DDevice9->GetStreamSource(StreamNumber,ppStreamData,OffsetInBytes,pStride)); +} + +HRESULT uMod_IDirect3DDevice9::SetStreamSourceFreq(UINT StreamNumber,UINT Divider) +{ + return(m_pIDirect3DDevice9->SetStreamSourceFreq(StreamNumber,Divider)); +} + +HRESULT uMod_IDirect3DDevice9::GetStreamSourceFreq(UINT StreamNumber,UINT* Divider) +{ + return(m_pIDirect3DDevice9->GetStreamSourceFreq(StreamNumber,Divider)); +} + +HRESULT uMod_IDirect3DDevice9::SetIndices(IDirect3DIndexBuffer9* pIndexData) +{ + return(m_pIDirect3DDevice9->SetIndices(pIndexData)); +} + +HRESULT uMod_IDirect3DDevice9::GetIndices(IDirect3DIndexBuffer9** ppIndexData) +{ + return(m_pIDirect3DDevice9->GetIndices(ppIndexData)); +} + +HRESULT uMod_IDirect3DDevice9::CreatePixelShader(CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader) +{ + return(m_pIDirect3DDevice9->CreatePixelShader(pFunction,ppShader)); +} + +HRESULT uMod_IDirect3DDevice9::SetPixelShader(IDirect3DPixelShader9* pShader) +{ + return(m_pIDirect3DDevice9->SetPixelShader(pShader)); +} + +HRESULT uMod_IDirect3DDevice9::GetPixelShader(IDirect3DPixelShader9** ppShader) +{ + return(m_pIDirect3DDevice9->GetPixelShader(ppShader)); +} + +HRESULT uMod_IDirect3DDevice9::SetPixelShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) +{ + return(m_pIDirect3DDevice9->SetPixelShaderConstantF(StartRegister,pConstantData,Vector4fCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetPixelShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount) +{ + return(m_pIDirect3DDevice9->GetPixelShaderConstantF(StartRegister,pConstantData,Vector4fCount)); +} + +HRESULT uMod_IDirect3DDevice9::SetPixelShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) +{ + return(m_pIDirect3DDevice9->SetPixelShaderConstantI(StartRegister,pConstantData,Vector4iCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetPixelShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount) +{ + return(m_pIDirect3DDevice9->GetPixelShaderConstantI(StartRegister,pConstantData,Vector4iCount)); +} + +HRESULT uMod_IDirect3DDevice9::SetPixelShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) +{ + return(m_pIDirect3DDevice9->SetPixelShaderConstantB(StartRegister,pConstantData,BoolCount)); +} + +HRESULT uMod_IDirect3DDevice9::GetPixelShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount) +{ + return(m_pIDirect3DDevice9->GetPixelShaderConstantB(StartRegister,pConstantData,BoolCount)); +} + +HRESULT uMod_IDirect3DDevice9::DrawRectPatch(UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo) +{ + return(m_pIDirect3DDevice9->DrawRectPatch(Handle,pNumSegs, pRectPatchInfo)); +} + +HRESULT uMod_IDirect3DDevice9::DrawTriPatch(UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo) +{ + return(m_pIDirect3DDevice9->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo)); +} + +HRESULT uMod_IDirect3DDevice9::DeletePatch(UINT Handle) +{ + return(m_pIDirect3DDevice9->DeletePatch(Handle)); +} + +HRESULT uMod_IDirect3DDevice9::CreateQuery(D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery) +{ + return(m_pIDirect3DDevice9->CreateQuery(Type,ppQuery)); +} + + diff --git a/uMod2/uMod_DX9/uMod_IDirect3DDevice9.h b/uMod2/uMod_DX9/uMod_IDirect3DDevice9.h new file mode 100644 index 0000000..aaa10ea --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DDevice9.h @@ -0,0 +1,212 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +/* + * + * BIG THANKS TO Michael Koch + * (proxydll_9.zip) + * + */ + + +#ifndef uMod_IDirect3DDevice9_H_ +#define uMod_IDirect3DDevice9_H_ + +#include +#include +#include "uMod_IDirect3DTexture9.h" +#include "uMod_IDirect3DVolumeTexture9.h" +#include "uMod_IDirect3DCubeTexture9.h" + + +class uMod_IDirect3DDevice9 : public IDirect3DDevice9 +{ +public: + uMod_IDirect3DDevice9(IDirect3DDevice9* pOriginal, uMod_TextureServer* server, int back_buffer_count); + virtual ~uMod_IDirect3DDevice9(void); + + // START: The original DX9 function definitions + HRESULT __stdcall QueryInterface (REFIID riid, void** ppvObj); + ULONG __stdcall AddRef(void); + ULONG __stdcall Release(void); + HRESULT __stdcall TestCooperativeLevel(void); + UINT __stdcall GetAvailableTextureMem(void); + HRESULT __stdcall EvictManagedResources(void); + HRESULT __stdcall GetDirect3D(IDirect3D9** ppD3D9); + HRESULT __stdcall GetDeviceCaps(D3DCAPS9* pCaps); + HRESULT __stdcall GetDisplayMode(UINT iSwapChain,D3DDISPLAYMODE* pMode); + HRESULT __stdcall GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters); + HRESULT __stdcall SetCursorProperties(UINT XHotSpot,UINT YHotSpot,IDirect3DSurface9* pCursorBitmap); + void __stdcall SetCursorPosition(int X,int Y,DWORD Flags); + BOOL __stdcall ShowCursor(BOOL bShow); + HRESULT __stdcall CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DSwapChain9** pSwapChain) ; + HRESULT __stdcall GetSwapChain(UINT iSwapChain,IDirect3DSwapChain9** pSwapChain); + UINT __stdcall GetNumberOfSwapChains(void); + HRESULT __stdcall Reset(D3DPRESENT_PARAMETERS* pPresentationParameters); + HRESULT __stdcall Present(CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion); + HRESULT __stdcall GetBackBuffer(UINT iSwapChain,UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer); + HRESULT __stdcall GetRasterStatus(UINT iSwapChain,D3DRASTER_STATUS* pRasterStatus); + HRESULT __stdcall SetDialogBoxMode(BOOL bEnableDialogs); + void __stdcall SetGammaRamp(UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp); + void __stdcall GetGammaRamp(UINT iSwapChain,D3DGAMMARAMP* pRamp); + HRESULT __stdcall CreateTexture(UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateVolumeTexture(UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateCubeTexture(UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateVertexBuffer(UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle); + HRESULT __stdcall CreateIndexBuffer(UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,HANDLE* pSharedHandle); + HRESULT __stdcall CreateRenderTarget(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall CreateDepthStencilSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall UpdateSurface(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestinationSurface,CONST POINT* pDestPoint); + HRESULT __stdcall UpdateTexture(IDirect3DBaseTexture9* pSourceTexture,IDirect3DBaseTexture9* pDestinationTexture); + HRESULT __stdcall GetRenderTargetData(IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface); + HRESULT __stdcall GetFrontBufferData(UINT iSwapChain,IDirect3DSurface9* pDestSurface); + HRESULT __stdcall StretchRect(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter); + HRESULT __stdcall ColorFill(IDirect3DSurface9* pSurface,CONST RECT* pRect,D3DCOLOR color); + HRESULT __stdcall CreateOffscreenPlainSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall SetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget); + HRESULT __stdcall GetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget); + HRESULT __stdcall SetDepthStencilSurface(IDirect3DSurface9* pNewZStencil); + HRESULT __stdcall GetDepthStencilSurface(IDirect3DSurface9** ppZStencilSurface); + HRESULT __stdcall BeginScene(void); + HRESULT __stdcall EndScene(void); + HRESULT __stdcall Clear(DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil); + HRESULT __stdcall SetTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix); + HRESULT __stdcall GetTransform(D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix); + HRESULT __stdcall MultiplyTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix); + HRESULT __stdcall SetViewport(CONST D3DVIEWPORT9* pViewport); + HRESULT __stdcall GetViewport(D3DVIEWPORT9* pViewport); + HRESULT __stdcall SetMaterial(CONST D3DMATERIAL9* pMaterial); + HRESULT __stdcall GetMaterial(D3DMATERIAL9* pMaterial); + HRESULT __stdcall SetLight(DWORD Index,CONST D3DLIGHT9* pLight); + HRESULT __stdcall GetLight(DWORD Index,D3DLIGHT9* pLight); + HRESULT __stdcall LightEnable(DWORD Index,BOOL Enable); + HRESULT __stdcall GetLightEnable(DWORD Index,BOOL* pEnable); + HRESULT __stdcall SetClipPlane(DWORD Index,CONST float* pPlane); + HRESULT __stdcall GetClipPlane(DWORD Index,float* pPlane); + HRESULT __stdcall SetRenderState(D3DRENDERSTATETYPE State,DWORD Value); + HRESULT __stdcall GetRenderState(D3DRENDERSTATETYPE State,DWORD* pValue); + HRESULT __stdcall CreateStateBlock(D3DSTATEBLOCKTYPE Type,IDirect3DStateBlock9** ppSB); + HRESULT __stdcall BeginStateBlock(void); + HRESULT __stdcall EndStateBlock(IDirect3DStateBlock9** ppSB); + HRESULT __stdcall SetClipStatus(CONST D3DCLIPSTATUS9* pClipStatus); + HRESULT __stdcall GetClipStatus(D3DCLIPSTATUS9* pClipStatus); + HRESULT __stdcall GetTexture(DWORD Stage,IDirect3DBaseTexture9** ppTexture); + HRESULT __stdcall SetTexture(DWORD Stage,IDirect3DBaseTexture9* pTexture); + HRESULT __stdcall GetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue); + HRESULT __stdcall SetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value); + HRESULT __stdcall GetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD* pValue); + HRESULT __stdcall SetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value); + HRESULT __stdcall ValidateDevice(DWORD* pNumPasses); + HRESULT __stdcall SetPaletteEntries(UINT PaletteNumber,CONST PALETTEENTRY* pEntries); + HRESULT __stdcall GetPaletteEntries(UINT PaletteNumber,PALETTEENTRY* pEntries); + HRESULT __stdcall SetCurrentTexturePalette(UINT PaletteNumber); + HRESULT __stdcall GetCurrentTexturePalette(UINT *PaletteNumber); + HRESULT __stdcall SetScissorRect(CONST RECT* pRect); + HRESULT __stdcall GetScissorRect( RECT* pRect); + HRESULT __stdcall SetSoftwareVertexProcessing(BOOL bSoftware); + BOOL __stdcall GetSoftwareVertexProcessing(void); + HRESULT __stdcall SetNPatchMode(float nSegments); + float __stdcall GetNPatchMode(void); + HRESULT __stdcall DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount); + HRESULT __stdcall DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount); + HRESULT __stdcall DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride); + HRESULT __stdcall DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride); + HRESULT __stdcall ProcessVertices(UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer9* pDestBuffer,IDirect3DVertexDeclaration9* pVertexDecl,DWORD Flags); + HRESULT __stdcall CreateVertexDeclaration(CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl); + HRESULT __stdcall SetVertexDeclaration(IDirect3DVertexDeclaration9* pDecl); + HRESULT __stdcall GetVertexDeclaration(IDirect3DVertexDeclaration9** ppDecl); + HRESULT __stdcall SetFVF(DWORD FVF); + HRESULT __stdcall GetFVF(DWORD* pFVF); + HRESULT __stdcall CreateVertexShader(CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader); + HRESULT __stdcall SetVertexShader(IDirect3DVertexShader9* pShader); + HRESULT __stdcall GetVertexShader(IDirect3DVertexShader9** ppShader); + HRESULT __stdcall SetVertexShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall GetVertexShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall SetVertexShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall GetVertexShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall SetVertexShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall GetVertexShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall SetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride); + HRESULT __stdcall GetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9** ppStreamData,UINT* OffsetInBytes,UINT* pStride); + HRESULT __stdcall SetStreamSourceFreq(UINT StreamNumber,UINT Divider); + HRESULT __stdcall GetStreamSourceFreq(UINT StreamNumber,UINT* Divider); + HRESULT __stdcall SetIndices(IDirect3DIndexBuffer9* pIndexData); + HRESULT __stdcall GetIndices(IDirect3DIndexBuffer9** ppIndexData); + HRESULT __stdcall CreatePixelShader(CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader); + HRESULT __stdcall SetPixelShader(IDirect3DPixelShader9* pShader); + HRESULT __stdcall GetPixelShader(IDirect3DPixelShader9** ppShader); + HRESULT __stdcall SetPixelShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall GetPixelShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall SetPixelShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall GetPixelShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall SetPixelShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall GetPixelShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall DrawRectPatch(UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo); + HRESULT __stdcall DrawTriPatch(UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo); + HRESULT __stdcall DeletePatch(UINT Handle); + HRESULT __stdcall CreateQuery(D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery); + // END: The original DX9 function definitions + + + + uMod_TextureClient* GetuMod_Client(void) {return (uMod_Client);} + + uMod_IDirect3DTexture9* GetLastCreatedTexture(void) {return (LastCreatedTexture);} + int SetLastCreatedTexture(uMod_IDirect3DTexture9* pTexture) {LastCreatedTexture=pTexture; return (RETURN_OK);} + + uMod_IDirect3DVolumeTexture9* GetLastCreatedVolumeTexture(void) {return (LastCreatedVolumeTexture);} + int SetLastCreatedVolumeTexture(uMod_IDirect3DVolumeTexture9* pTexture) {LastCreatedVolumeTexture=pTexture; return (RETURN_OK);} + + uMod_IDirect3DCubeTexture9* GetLastCreatedCubeTexture(void) {return (LastCreatedCubeTexture);} + int SetLastCreatedCubeTexture(uMod_IDirect3DCubeTexture9* pTexture) {LastCreatedCubeTexture=pTexture; return (RETURN_OK);} + + + uMod_IDirect3DTexture9* GetSingleTexture(void) {return (SingleTexture);} + uMod_IDirect3DVolumeTexture9* GetSingleVolumeTexture(void) {return (SingleVolumeTexture);} + uMod_IDirect3DCubeTexture9* GetSingleCubeTexture(void) {return (SingleCubeTexture);} + + + private: + int CreateSingleTexture(void); + IDirect3DDevice9* m_pIDirect3DDevice9; + + int CounterSaveSingleTexture; + uMod_IDirect3DTexture9* SingleTexture; + uMod_IDirect3DVolumeTexture9* SingleVolumeTexture; + uMod_IDirect3DCubeTexture9* SingleCubeTexture; + char SingleTextureMod; + + D3DCOLOR TextureColour; + ID3DXFont *OSD_Font; + //D3DCOLOR FontColour; + int BackBufferCount; + bool NormalRendering; + + int uMod_Reference; + + uMod_IDirect3DTexture9* LastCreatedTexture; + uMod_IDirect3DVolumeTexture9* LastCreatedVolumeTexture; + uMod_IDirect3DCubeTexture9* LastCreatedCubeTexture; + + uMod_TextureServer* uMod_Server; + uMod_TextureClient* uMod_Client; +}; + +#endif + diff --git a/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp b/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp new file mode 100644 index 0000000..1cf90e7 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.cpp @@ -0,0 +1,116 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + +#define uMod_IDirect3DDevice9 uMod_IDirect3DDevice9Ex +#define IDirect3DDevice9 IDirect3DDevice9Ex +#define m_pIDirect3DDevice9 m_pIDirect3DDevice9Ex + +#define RETURN_QueryInterface 0x01000001L +#define PRE_MESSAGE "uMod_IDirect3DDevice9Ex" + + +#include "uMod_IDirect3DDevice9.cpp" + + + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::CheckDeviceState( HWND hWindow) +{ + return(m_pIDirect3DDevice9Ex->CheckDeviceState( hWindow)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::CheckResourceResidency( IDirect3DResource9 **ppResourceArray, UINT32 NumResources) +{ + return(m_pIDirect3DDevice9Ex->CheckResourceResidency( ppResourceArray, NumResources)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::ComposeRects( IDirect3DSurface9 *pSource, IDirect3DSurface9 *pDestination, IDirect3DVertexBuffer9 *pSrcRectDescriptors, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescriptors, D3DCOMPOSERECTSOP Operation, INT XOffset, INT YOffset) +{ + return(m_pIDirect3DDevice9Ex->ComposeRects( pSource, pDestination, pSrcRectDescriptors, NumRects, pDstRectDescriptors, Operation, XOffset, YOffset)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx( UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) +{ + return(m_pIDirect3DDevice9Ex->CreateDepthStencilSurfaceEx( Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle, Usage)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx( UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) +{ + return(m_pIDirect3DDevice9Ex->CreateOffscreenPlainSurfaceEx( Width, Height, Format, Pool, ppSurface, pSharedHandle, Usage)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::CreateRenderTargetEx( UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage) +{ + return(m_pIDirect3DDevice9Ex->CreateRenderTargetEx( Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle, Usage)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::GetDisplayModeEx( UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation) +{ + return(m_pIDirect3DDevice9Ex->GetDisplayModeEx( iSwapChain, pMode, pRotation)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::GetGPUThreadPriority( INT *pPriority) +{ + return(m_pIDirect3DDevice9Ex->GetGPUThreadPriority( pPriority)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::GetMaximumFrameLatency( UINT *pMaxLatency) +{ + return(m_pIDirect3DDevice9Ex->GetMaximumFrameLatency( pMaxLatency)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::PresentEx( const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags) +{ + return(m_pIDirect3DDevice9Ex->PresentEx( pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::ResetEx( D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode) +{ + return(m_pIDirect3DDevice9Ex->ResetEx( pPresentationParameters, pFullscreenDisplayMode)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::SetConvolutionMonoKernel( UINT Width, UINT Height, float *RowWeights, float *ColumnWeights) +{ + return(m_pIDirect3DDevice9Ex->SetConvolutionMonoKernel( Width, Height, RowWeights, ColumnWeights)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::SetGPUThreadPriority( INT pPriority) +{ + return(m_pIDirect3DDevice9Ex->SetGPUThreadPriority( pPriority)); +} + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::SetMaximumFrameLatency( UINT pMaxLatency) +{ + return(m_pIDirect3DDevice9Ex->SetMaximumFrameLatency( pMaxLatency)); +} + +/* +HRESULT __stdcall uMod_IDirect3DDevice9Ex::TestCooperativeLevel() +{ + return(m_pIDirect3DDevice9Ex->TestCooperativeLevel()); +} +*/ + +HRESULT __stdcall uMod_IDirect3DDevice9Ex::WaitForVBlank( UINT SwapChainIndex) +{ + return(m_pIDirect3DDevice9Ex->WaitForVBlank( SwapChainIndex)); +} + diff --git a/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h b/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h new file mode 100644 index 0000000..c7daeca --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DDevice9Ex.h @@ -0,0 +1,225 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +#ifndef uMod_IDirect3DDevice9Ex_H_ +#define uMod_IDirect3DDevice9Ex_H_ + +#include +#include +#include "uMod_IDirect3DTexture9.h" +#include "uMod_IDirect3DVolumeTexture9.h" +#include "uMod_IDirect3DCubeTexture9.h" + + +class uMod_IDirect3DDevice9Ex : public IDirect3DDevice9Ex +{ +public: + uMod_IDirect3DDevice9Ex( IDirect3DDevice9Ex* pOriginal, uMod_TextureServer* server, int back_buffer_count); + virtual ~uMod_IDirect3DDevice9Ex(void); + + // START: The original DX9 function definitions + HRESULT __stdcall QueryInterface (REFIID riid, void** ppvObj); + ULONG __stdcall AddRef(void); + ULONG __stdcall Release(void); + HRESULT __stdcall TestCooperativeLevel(void); + UINT __stdcall GetAvailableTextureMem(void); + HRESULT __stdcall EvictManagedResources(void); + HRESULT __stdcall GetDirect3D(IDirect3D9** ppD3D9); + HRESULT __stdcall GetDeviceCaps(D3DCAPS9* pCaps); + HRESULT __stdcall GetDisplayMode(UINT iSwapChain,D3DDISPLAYMODE* pMode); + HRESULT __stdcall GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters); + HRESULT __stdcall SetCursorProperties(UINT XHotSpot,UINT YHotSpot,IDirect3DSurface9* pCursorBitmap); + void __stdcall SetCursorPosition(int X,int Y,DWORD Flags); + BOOL __stdcall ShowCursor(BOOL bShow); + HRESULT __stdcall CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DSwapChain9** pSwapChain) ; + HRESULT __stdcall GetSwapChain(UINT iSwapChain,IDirect3DSwapChain9** pSwapChain); + UINT __stdcall GetNumberOfSwapChains(void); + HRESULT __stdcall Reset(D3DPRESENT_PARAMETERS* pPresentationParameters); + HRESULT __stdcall Present(CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion); + HRESULT __stdcall GetBackBuffer(UINT iSwapChain,UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer); + HRESULT __stdcall GetRasterStatus(UINT iSwapChain,D3DRASTER_STATUS* pRasterStatus); + HRESULT __stdcall SetDialogBoxMode(BOOL bEnableDialogs); + void __stdcall SetGammaRamp(UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp); + void __stdcall GetGammaRamp(UINT iSwapChain,D3DGAMMARAMP* pRamp); + HRESULT __stdcall CreateTexture(UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateVolumeTexture(UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateCubeTexture(UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,HANDLE* pSharedHandle); + HRESULT __stdcall CreateVertexBuffer(UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle); + HRESULT __stdcall CreateIndexBuffer(UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,HANDLE* pSharedHandle); + HRESULT __stdcall CreateRenderTarget(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall CreateDepthStencilSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall UpdateSurface(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestinationSurface,CONST POINT* pDestPoint); + HRESULT __stdcall UpdateTexture(IDirect3DBaseTexture9* pSourceTexture,IDirect3DBaseTexture9* pDestinationTexture); + HRESULT __stdcall GetRenderTargetData(IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface); + HRESULT __stdcall GetFrontBufferData(UINT iSwapChain,IDirect3DSurface9* pDestSurface); + HRESULT __stdcall StretchRect(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter); + HRESULT __stdcall ColorFill(IDirect3DSurface9* pSurface,CONST RECT* pRect,D3DCOLOR color); + HRESULT __stdcall CreateOffscreenPlainSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle); + HRESULT __stdcall SetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget); + HRESULT __stdcall GetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget); + HRESULT __stdcall SetDepthStencilSurface(IDirect3DSurface9* pNewZStencil); + HRESULT __stdcall GetDepthStencilSurface(IDirect3DSurface9** ppZStencilSurface); + HRESULT __stdcall BeginScene(void); + HRESULT __stdcall EndScene(void); + HRESULT __stdcall Clear(DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil); + HRESULT __stdcall SetTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix); + HRESULT __stdcall GetTransform(D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix); + HRESULT __stdcall MultiplyTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix); + HRESULT __stdcall SetViewport(CONST D3DVIEWPORT9* pViewport); + HRESULT __stdcall GetViewport(D3DVIEWPORT9* pViewport); + HRESULT __stdcall SetMaterial(CONST D3DMATERIAL9* pMaterial); + HRESULT __stdcall GetMaterial(D3DMATERIAL9* pMaterial); + HRESULT __stdcall SetLight(DWORD Index,CONST D3DLIGHT9* pLight); + HRESULT __stdcall GetLight(DWORD Index,D3DLIGHT9* pLight); + HRESULT __stdcall LightEnable(DWORD Index,BOOL Enable); + HRESULT __stdcall GetLightEnable(DWORD Index,BOOL* pEnable); + HRESULT __stdcall SetClipPlane(DWORD Index,CONST float* pPlane); + HRESULT __stdcall GetClipPlane(DWORD Index,float* pPlane); + HRESULT __stdcall SetRenderState(D3DRENDERSTATETYPE State,DWORD Value); + HRESULT __stdcall GetRenderState(D3DRENDERSTATETYPE State,DWORD* pValue); + HRESULT __stdcall CreateStateBlock(D3DSTATEBLOCKTYPE Type,IDirect3DStateBlock9** ppSB); + HRESULT __stdcall BeginStateBlock(void); + HRESULT __stdcall EndStateBlock(IDirect3DStateBlock9** ppSB); + HRESULT __stdcall SetClipStatus(CONST D3DCLIPSTATUS9* pClipStatus); + HRESULT __stdcall GetClipStatus(D3DCLIPSTATUS9* pClipStatus); + HRESULT __stdcall GetTexture(DWORD Stage,IDirect3DBaseTexture9** ppTexture); + HRESULT __stdcall SetTexture(DWORD Stage,IDirect3DBaseTexture9* pTexture); + HRESULT __stdcall GetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue); + HRESULT __stdcall SetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value); + HRESULT __stdcall GetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD* pValue); + HRESULT __stdcall SetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value); + HRESULT __stdcall ValidateDevice(DWORD* pNumPasses); + HRESULT __stdcall SetPaletteEntries(UINT PaletteNumber,CONST PALETTEENTRY* pEntries); + HRESULT __stdcall GetPaletteEntries(UINT PaletteNumber,PALETTEENTRY* pEntries); + HRESULT __stdcall SetCurrentTexturePalette(UINT PaletteNumber); + HRESULT __stdcall GetCurrentTexturePalette(UINT *PaletteNumber); + HRESULT __stdcall SetScissorRect(CONST RECT* pRect); + HRESULT __stdcall GetScissorRect( RECT* pRect); + HRESULT __stdcall SetSoftwareVertexProcessing(BOOL bSoftware); + BOOL __stdcall GetSoftwareVertexProcessing(void); + HRESULT __stdcall SetNPatchMode(float nSegments); + float __stdcall GetNPatchMode(void); + HRESULT __stdcall DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount); + HRESULT __stdcall DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount); + HRESULT __stdcall DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride); + HRESULT __stdcall DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride); + HRESULT __stdcall ProcessVertices(UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer9* pDestBuffer,IDirect3DVertexDeclaration9* pVertexDecl,DWORD Flags); + HRESULT __stdcall CreateVertexDeclaration(CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl); + HRESULT __stdcall SetVertexDeclaration(IDirect3DVertexDeclaration9* pDecl); + HRESULT __stdcall GetVertexDeclaration(IDirect3DVertexDeclaration9** ppDecl); + HRESULT __stdcall SetFVF(DWORD FVF); + HRESULT __stdcall GetFVF(DWORD* pFVF); + HRESULT __stdcall CreateVertexShader(CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader); + HRESULT __stdcall SetVertexShader(IDirect3DVertexShader9* pShader); + HRESULT __stdcall GetVertexShader(IDirect3DVertexShader9** ppShader); + HRESULT __stdcall SetVertexShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall GetVertexShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall SetVertexShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall GetVertexShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall SetVertexShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall GetVertexShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall SetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride); + HRESULT __stdcall GetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9** ppStreamData,UINT* OffsetInBytes,UINT* pStride); + HRESULT __stdcall SetStreamSourceFreq(UINT StreamNumber,UINT Divider); + HRESULT __stdcall GetStreamSourceFreq(UINT StreamNumber,UINT* Divider); + HRESULT __stdcall SetIndices(IDirect3DIndexBuffer9* pIndexData); + HRESULT __stdcall GetIndices(IDirect3DIndexBuffer9** ppIndexData); + HRESULT __stdcall CreatePixelShader(CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader); + HRESULT __stdcall SetPixelShader(IDirect3DPixelShader9* pShader); + HRESULT __stdcall GetPixelShader(IDirect3DPixelShader9** ppShader); + HRESULT __stdcall SetPixelShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall GetPixelShaderConstantF(UINT StartRegister,float* pConstantData,UINT Vector4fCount); + HRESULT __stdcall SetPixelShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall GetPixelShaderConstantI(UINT StartRegister,int* pConstantData,UINT Vector4iCount); + HRESULT __stdcall SetPixelShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall GetPixelShaderConstantB(UINT StartRegister,BOOL* pConstantData,UINT BoolCount); + HRESULT __stdcall DrawRectPatch(UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo); + HRESULT __stdcall DrawTriPatch(UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo); + HRESULT __stdcall DeletePatch(UINT Handle); + HRESULT __stdcall CreateQuery(D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery); + + + + HRESULT __stdcall CheckDeviceState( HWND hWindow); + HRESULT __stdcall CheckResourceResidency( IDirect3DResource9 **pResourceArray, UINT32 NumResources); + HRESULT __stdcall ComposeRects( IDirect3DSurface9 *pSource, IDirect3DSurface9 *pDestination, IDirect3DVertexBuffer9 *pSrcRectDescriptors, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescriptors, D3DCOMPOSERECTSOP Operation, INT XOffset, INT YOffset); + HRESULT __stdcall CreateDepthStencilSurfaceEx( UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage); + HRESULT __stdcall CreateOffscreenPlainSurfaceEx( UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage); + HRESULT __stdcall CreateRenderTargetEx( UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage); + HRESULT __stdcall GetDisplayModeEx( UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation); + HRESULT __stdcall GetGPUThreadPriority( INT *pPriority); + HRESULT __stdcall GetMaximumFrameLatency( UINT *pMaxLatency); + HRESULT __stdcall PresentEx( const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags); + HRESULT __stdcall ResetEx( D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode); + HRESULT __stdcall SetConvolutionMonoKernel( UINT Width, UINT Height, float *RowWeights, float *ColumnWeights); + HRESULT __stdcall SetGPUThreadPriority( INT pPriority); + HRESULT __stdcall SetMaximumFrameLatency( UINT pMaxLatency); + //HRESULT __stdcall TestCooperativeLevel(); + HRESULT __stdcall WaitForVBlank( UINT SwapChainIndex); + + + // END: The original DX9 function definitions + + + uMod_TextureClient* GetuMod_Client(void) {return (uMod_Client);} + + uMod_IDirect3DTexture9* GetLastCreatedTexture(void) {return (LastCreatedTexture);} + int SetLastCreatedTexture(uMod_IDirect3DTexture9* pTexture) {LastCreatedTexture=pTexture; return (RETURN_OK);} + + uMod_IDirect3DVolumeTexture9* GetLastCreatedVolumeTexture(void) {return (LastCreatedVolumeTexture);} + int SetLastCreatedVolumeTexture(uMod_IDirect3DVolumeTexture9* pTexture) {LastCreatedVolumeTexture=pTexture; return (RETURN_OK);} + + uMod_IDirect3DCubeTexture9* GetLastCreatedCubeTexture(void) {return (LastCreatedCubeTexture);} + int SetLastCreatedCubeTexture(uMod_IDirect3DCubeTexture9* pTexture) {LastCreatedCubeTexture=pTexture; return (RETURN_OK);} + + + uMod_IDirect3DTexture9* GetSingleTexture(void) {return (SingleTexture);} + uMod_IDirect3DVolumeTexture9* GetSingleVolumeTexture(void) {return (SingleVolumeTexture);} + uMod_IDirect3DCubeTexture9* GetSingleCubeTexture(void) {return (SingleCubeTexture);} + + + + private: + int CreateSingleTexture(void); + IDirect3DDevice9Ex* m_pIDirect3DDevice9Ex; + + int CounterSaveSingleTexture; + uMod_IDirect3DTexture9* SingleTexture; + uMod_IDirect3DVolumeTexture9* SingleVolumeTexture; + uMod_IDirect3DCubeTexture9* SingleCubeTexture; + char SingleTextureMod; + + D3DCOLOR TextureColour; + ID3DXFont *OSD_Font; + //D3DCOLOR FontColour; + int BackBufferCount; + bool NormalRendering; + + int uMod_Reference; + + uMod_IDirect3DTexture9* LastCreatedTexture; + uMod_IDirect3DVolumeTexture9* LastCreatedVolumeTexture; + uMod_IDirect3DCubeTexture9* LastCreatedCubeTexture; + + uMod_TextureServer* uMod_Server; + uMod_TextureClient* uMod_Client; +}; + +#endif + diff --git a/uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp b/uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp new file mode 100644 index 0000000..d2a8506 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DTexture9.cpp @@ -0,0 +1,361 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + * some function (e.g. AddReff()) are presumed to work on the texture object which belong to them + * if this texture was switched, we must redirect this calls to the CrossRef_D3Dtex texture object + */ + + +#include "uMod_Main.h" + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::QueryInterface(REFIID riid, void** ppvObj) +{ + if (riid==IID_IDirect3D9) + { + // This function should never be called with IID_IDirect3D9 by the game + // thus this call comes from our own dll to ask for the texture type + // 0x01000000L == uMod_IDirect3DTexture9 + // 0x01000001L == uMod_IDirect3DVolumeTexture9 + // 0x01000002L == uMod_IDirect3DCubeTexture9 + + *ppvObj = this; + return (0x01000000L); + } + HRESULT hRes; + if (CrossRef_D3Dtex!=NULL) + { + hRes = CrossRef_D3Dtex->m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==CrossRef_D3Dtex->m_D3Dtex) *ppvObj=this; + } + else + { + hRes = m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==m_D3Dtex) *ppvObj=this; + } + return (hRes); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DTexture9::AddRef() +{ + if (FAKE) return (1); //bug, this case should never happen + if (CrossRef_D3Dtex!=NULL) + { + return (CrossRef_D3Dtex->m_D3Dtex->AddRef()); + } + else return (m_D3Dtex->AddRef()); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DTexture9::Release() +{ + Message("uMod_IDirect3DTexture9::Release(): %lu\n", this); + + void *cpy; + long ret = m_D3Ddev->QueryInterface( IID_IDirect3DTexture9, &cpy); + + ULONG count; + if (FAKE) + { + UnswitchTextures( this); + count = m_D3Dtex->Release(); //count must be zero, cause we don't call AddRef of fake_textures + } + else + { + if (CrossRef_D3Dtex!=NULL) //if this texture is switched with a fake texture + { + uMod_IDirect3DTexture9 *fake_texture = CrossRef_D3Dtex; + count = fake_texture->m_D3Dtex->Release(); //release the original texture + if (count==0) //if texture is released we switch the textures back + { + UnswitchTextures(this); + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetSingleTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetSingleTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + } + } + else + { + count = m_D3Dtex->Release(); + } + } + + if (count==0) //if this texture is released, we clean up + { + // if this texture is the LastCreatedTexture, the next time LastCreatedTexture would be added, + // the hash of a non existing texture would be calculated + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetLastCreatedTexture()==this) ((uMod_IDirect3DDevice9*) m_D3Ddev)->SetLastCreatedTexture( NULL); + else ((uMod_IDirect3DDevice9*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetLastCreatedTexture()==this) ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->SetLastCreatedTexture( NULL); + else ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + + delete(this); + } + + Message("uMod_IDirect3DTexture9::Release() end: %lu\n", this); + return (count); +} + +HRESULT APIENTRY uMod_IDirect3DTexture9::GetDevice(IDirect3DDevice9** ppDevice) +{ + *ppDevice = m_D3Ddev; + return D3D_OK; +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); + return (m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); + return (m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::FreePrivateData(REFGUID refguid) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->FreePrivateData(refguid)); + return (m_D3Dtex->FreePrivateData(refguid)); +} + +DWORD APIENTRY uMod_IDirect3DTexture9::SetPriority(DWORD PriorityNew) +{ + return (m_D3Dtex->SetPriority(PriorityNew)); +} + +DWORD APIENTRY uMod_IDirect3DTexture9::GetPriority() +{ + return (m_D3Dtex->GetPriority()); +} + +void APIENTRY uMod_IDirect3DTexture9::PreLoad() +{ + m_D3Dtex->PreLoad(); +} + +D3DRESOURCETYPE APIENTRY uMod_IDirect3DTexture9::GetType() +{ + return (m_D3Dtex->GetType()); +} + +DWORD APIENTRY uMod_IDirect3DTexture9::SetLOD(DWORD LODNew) +{ + return (m_D3Dtex->SetLOD(LODNew)); +} + +DWORD APIENTRY uMod_IDirect3DTexture9::GetLOD() +{ + return (m_D3Dtex->GetLOD()); +} + +DWORD APIENTRY uMod_IDirect3DTexture9::GetLevelCount() +{ + return (m_D3Dtex->GetLevelCount()); +} + +HRESULT APIENTRY uMod_IDirect3DTexture9::SetAutoGenFilterType(D3DTEXTUREFILTERTYPE FilterType) +{ + return (m_D3Dtex->SetAutoGenFilterType(FilterType)); +} + +D3DTEXTUREFILTERTYPE APIENTRY uMod_IDirect3DTexture9::GetAutoGenFilterType() +{ + return (m_D3Dtex->GetAutoGenFilterType()); +} + +void APIENTRY uMod_IDirect3DTexture9::GenerateMipSubLevels() +{ + m_D3Dtex->GenerateMipSubLevels(); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::GetLevelDesc(UINT Level,D3DSURFACE_DESC *pDesc) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetLevelDesc(Level, pDesc)); + return (m_D3Dtex->GetLevelDesc(Level, pDesc)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::GetSurfaceLevel(UINT Level,IDirect3DSurface9** ppSurfaceLevel) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetSurfaceLevel(Level, ppSurfaceLevel)); + return (m_D3Dtex->GetSurfaceLevel(Level, ppSurfaceLevel)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::LockRect(UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->LockRect(Level, pLockedRect, pRect, Flags)); + return (m_D3Dtex->LockRect(Level, pLockedRect, pRect, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::UnlockRect(UINT Level) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->UnlockRect(Level)); + return (m_D3Dtex->UnlockRect(Level)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DTexture9::AddDirtyRect(CONST RECT* pDirtyRect) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->AddDirtyRect(pDirtyRect)); + return (m_D3Dtex->AddDirtyRect(pDirtyRect)); +} + + +int uMod_IDirect3DTexture9::GetHash(MyTypeHash &hash) +{ + hash=0u; + if (FAKE) return (RETURN_BAD_ARGUMENT); + IDirect3DTexture9 *pTexture = m_D3Dtex; + if (CrossRef_D3Dtex!=NULL) pTexture = CrossRef_D3Dtex->m_D3Dtex; + + IDirect3DSurface9 *pOffscreenSurface = NULL; + //IDirect3DTexture9 *pOffscreenTexture = NULL; + IDirect3DSurface9 *pResolvedSurface = NULL; + D3DLOCKED_RECT d3dlr; + D3DSURFACE_DESC desc; + bool normal_lock=true; + + if (pTexture->GetLevelDesc(0, &desc)!=D3D_OK) //get the format and the size of the texture + { + Message("uMod_IDirect3DTexture9::GetHash() Failed: GetLevelDesc \n"); + return (RETURN_GetLevelDesc_FAILED); + } + + Message("uMod_IDirect3DTexture9::GetHash() (%d %d) F%d T%d U%d P%d M(%d %d)\n", desc.Width, desc.Height, + desc.Format, desc.Type, desc.Usage, desc.Pool, desc.MultiSampleType, desc.MultiSampleQuality); + + + if (desc.Pool!=D3DPOOL_DEFAULT) + { + if (pTexture->LockRect( 0, &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + normal_lock = false; + Message("uMod_IDirect3DTexture9::GetHash() Failed: LockRect 1\n"); + if (pTexture->GetSurfaceLevel(0, &pResolvedSurface)!=D3D_OK) + { + Message("uMod_IDirect3DTexture9::GetHash() Failed: GetSurfaceLevel\n"); + //return (RETURN_LockRect_FAILED); + pResolvedSurface = NULL; + } + else if (pResolvedSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + pResolvedSurface->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: LockRect 2\n"); + pResolvedSurface = NULL; + //return (RETURN_LockRect_FAILED); + } + } + } + if (desc.Pool==D3DPOOL_DEFAULT || (!normal_lock && pResolvedSurface==NULL))//desc.Pool==D3DPOOL_DEFAULT) //get the raw data of the texture + { + //Message("uMod_IDirect3DTexture9::GetHash() (D3DPOOL_DEFAULT)\n"); + + IDirect3DSurface9 *pSurfaceLevel_orig = NULL; + if (pTexture->GetSurfaceLevel( 0, &pSurfaceLevel_orig)!=D3D_OK) + { + Message("uMod_IDirect3DTexture9::GetHash() Failed: GetSurfaceLevel 1 (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + if (desc.MultiSampleType != D3DMULTISAMPLE_NONE) + { + //Message("uMod_IDirect3DTexture9::GetHash() MultiSampleType\n"); + if (D3D_OK!=m_D3Ddev->CreateRenderTarget( desc.Width, desc.Height, desc.Format, D3DMULTISAMPLE_NONE, 0, FALSE, &pResolvedSurface, NULL )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: CreateRenderTarget (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + if (D3D_OK!=m_D3Ddev->StretchRect( pSurfaceLevel_orig, NULL, pResolvedSurface, NULL, D3DTEXF_NONE )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: StretchRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + pSurfaceLevel_orig = pResolvedSurface; + } + + if (D3D_OK!=m_D3Ddev->CreateOffscreenPlainSurface( desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &pOffscreenSurface, NULL)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: CreateOffscreenPlainSurface (D3DPOOL_DEFAULT)\n"); + return (RETURN_TEXTURE_NOT_LOADED); + } + + if (D3D_OK!=m_D3Ddev->GetRenderTargetData( pSurfaceLevel_orig, pOffscreenSurface)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: GetRenderTargetData (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + pSurfaceLevel_orig->Release(); + + if (pOffscreenSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DTexture9::GetHash() Failed: LockRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + } + + int size = (GetBitsFromFormat( desc.Format) * desc.Width*desc.Height)/8; + + hash = GetCRC32( (char*) d3dlr.pBits, size); //calculate the crc32 of the texture + + if (pOffscreenSurface!=NULL) + { + pOffscreenSurface->UnlockRect(); + pOffscreenSurface->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + } + else if (pResolvedSurface!=NULL) + { + pResolvedSurface->UnlockRect(); + pResolvedSurface->Release(); + } + else pTexture->UnlockRect(0); + + Message("uMod_IDirect3DTexture9::GetHash() %#lX (%d %d) %d = %d\n", hash, desc.Width, desc.Height, desc.Format, size); + return (RETURN_OK); +} diff --git a/uMod2/uMod_DX9/uMod_IDirect3DTexture9.h b/uMod2/uMod_DX9/uMod_IDirect3DTexture9.h new file mode 100644 index 0000000..bef1bec --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DTexture9.h @@ -0,0 +1,124 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +/* + * + * BIG THANKS TO Matthew L (Azorbix) + * (Direct3D StarterKit v3.0) + * + */ + + +#ifndef uMod_IDirect3DTexture9_H +#define uMod_IDirect3DTexture9_H + +#include +#include + +#include "uMod_Defines.h" + + + +interface uMod_IDirect3DTexture9 : public IDirect3DTexture9 +{ + uMod_IDirect3DTexture9(IDirect3DTexture9 **ppTex, IDirect3DDevice9 *pIDirect3DDevice9) + { + m_D3Dtex = *ppTex; //Texture which will be displayed and will be passed to the game + m_D3Ddev = pIDirect3DDevice9; //device pointer + CrossRef_D3Dtex = NULL; //cross reference + // fake texture: store the pointer to the original uMod_IDirect3DTexture9 object, needed if a fake texture is unselected + // original texture: stores the pointer to the fake texture object, is needed if original texture is deleted, + // thus the fake texture can also be deleted + Reference = -1; //need for fast deleting + Hash = 0u; + FAKE = false; + } + + // callback interface + IDirect3DTexture9 *m_D3Dtex; + uMod_IDirect3DTexture9 *CrossRef_D3Dtex; + IDirect3DDevice9 *m_D3Ddev; + int Reference; + MyTypeHash Hash; + bool FAKE; + + // original interface + STDMETHOD(QueryInterface) (REFIID riid, void** ppvObj); + STDMETHOD_(ULONG,AddRef)(); + STDMETHOD_(ULONG,Release)(); + STDMETHOD(GetDevice)(IDirect3DDevice9** ppDevice); + STDMETHOD(SetPrivateData)(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags); + STDMETHOD(GetPrivateData)(REFGUID refguid,void* pData,DWORD* pSizeOfData); + STDMETHOD(FreePrivateData)(REFGUID refguid); + STDMETHOD_(DWORD, SetPriority)(DWORD PriorityNew); + STDMETHOD_(DWORD, GetPriority)(); + STDMETHOD_(void, PreLoad)(); + STDMETHOD_(D3DRESOURCETYPE, GetType)(); + STDMETHOD_(DWORD, SetLOD)(DWORD LODNew); + STDMETHOD_(DWORD, GetLOD)(); + STDMETHOD_(DWORD, GetLevelCount)(); + STDMETHOD(SetAutoGenFilterType)(D3DTEXTUREFILTERTYPE FilterType); + STDMETHOD_(D3DTEXTUREFILTERTYPE, GetAutoGenFilterType)(); + STDMETHOD_(void, GenerateMipSubLevels)(); + STDMETHOD(GetLevelDesc)(UINT Level,D3DSURFACE_DESC *pDesc); + STDMETHOD(GetSurfaceLevel)(UINT Level,IDirect3DSurface9** ppSurfaceLevel); + STDMETHOD(LockRect)(UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags); + STDMETHOD(UnlockRect)(UINT Level); + STDMETHOD(AddDirtyRect)(CONST RECT* pDirtyRect); + + int GetHash(MyTypeHash &hash); +}; + + + +inline void UnswitchTextures(uMod_IDirect3DTexture9 *pTexture) +{ + uMod_IDirect3DTexture9* CrossRef = pTexture->CrossRef_D3Dtex; + if (CrossRef!=NULL) + { + // switch textures back + IDirect3DTexture9* cpy = pTexture->m_D3Dtex; + pTexture->m_D3Dtex = CrossRef->m_D3Dtex; + CrossRef->m_D3Dtex = cpy; + + // cancel the link + CrossRef->CrossRef_D3Dtex = NULL; + pTexture->CrossRef_D3Dtex = NULL; + } +} + +inline int SwitchTextures( uMod_IDirect3DTexture9 *pTexture1, uMod_IDirect3DTexture9 *pTexture2) +{ + if (pTexture1->m_D3Ddev == pTexture2->m_D3Ddev && pTexture1->CrossRef_D3Dtex == NULL && pTexture2->CrossRef_D3Dtex == NULL) + { + // make cross reference + pTexture1->CrossRef_D3Dtex = pTexture2; + pTexture2->CrossRef_D3Dtex = pTexture1; + + // switch textures + IDirect3DTexture9* cpy = pTexture2->m_D3Dtex; + pTexture2->m_D3Dtex = pTexture1->m_D3Dtex; + pTexture1->m_D3Dtex = cpy; + return (RETURN_OK); + } + else return (RETURN_TEXTURE_NOT_SWITCHED); +} + + +#endif diff --git a/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp b/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp new file mode 100644 index 0000000..a9942eb --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.cpp @@ -0,0 +1,385 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +/* + * some function (e.g. AddReff()) are presumed to work on the texture object which belong to them + * if this texture was switched, we must redirect this calls to the CrossRef_D3Dtex texture object + */ + + +#include "uMod_Main.h" + +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::QueryInterface(REFIID riid, void** ppvObj) +{ + if (riid==IID_IDirect3D9) + { + // This function should never be called with IID_IDirect3D9 by the game + // thus this call comes from our own dll to ask for the texture type + // 0x01000000L == uMod_IDirect3DTexture9 + // 0x01000001L == uMod_IDirect3DVolumeTexture9 + // 0x01000002L == uMod_IDirect3DCubeTexture9 + + *ppvObj = this; + return (0x01000001L); + } + HRESULT hRes; + if (CrossRef_D3Dtex!=NULL) + { + hRes = CrossRef_D3Dtex->m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==CrossRef_D3Dtex->m_D3Dtex) *ppvObj=this; + } + else + { + hRes = m_D3Dtex->QueryInterface(riid, ppvObj); + if (*ppvObj==m_D3Dtex) *ppvObj=this; + } + return (hRes); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DVolumeTexture9::AddRef() +{ + if (FAKE) return (1); //bug, this case should never happen + if (CrossRef_D3Dtex!=NULL) + { + return (CrossRef_D3Dtex->m_D3Dtex->AddRef()); + } + else return (m_D3Dtex->AddRef()); +} + +//this function yields for the non switched texture object +ULONG APIENTRY uMod_IDirect3DVolumeTexture9::Release() +{ + Message("uMod_IDirect3DVolumeTexture9::Release(): %lu\n", this); + + void *cpy; + long ret = m_D3Ddev->QueryInterface( IID_IDirect3DTexture9, &cpy); + + ULONG count; + if (FAKE) + { + UnswitchTextures( this); + count = m_D3Dtex->Release(); //count must be zero, cause we don't call AddRef of fake_textures + } + else + { + if (CrossRef_D3Dtex!=NULL) //if this texture is switched with a fake texture + { + uMod_IDirect3DVolumeTexture9 *fake_texture = CrossRef_D3Dtex; + count = fake_texture->m_D3Dtex->Release(); //release the original texture + if (count==0) //if texture is released we switch the textures back + { + UnswitchTextures(this); + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetSingleVolumeTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetSingleVolumeTexture()!=fake_texture) fake_texture->Release(); // we release the fake texture + } + } + } + else + { + count = m_D3Dtex->Release(); + } + } + + if (count==0) //if this texture is released, we clean up + { + // if this texture is the LastCreatedTexture, the next time LastCreatedTexture would be added, + // the hash of a non existing texture would be calculated + if (ret == 0x01000000L) + { + if (((uMod_IDirect3DDevice9*) m_D3Ddev)->GetLastCreatedVolumeTexture()==this) ((uMod_IDirect3DDevice9*) m_D3Ddev)->SetLastCreatedVolumeTexture( NULL); + else ((uMod_IDirect3DDevice9*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + else + { + if (((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetLastCreatedVolumeTexture()==this) ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->SetLastCreatedVolumeTexture( NULL); + else ((uMod_IDirect3DDevice9Ex*) m_D3Ddev)->GetuMod_Client()->RemoveTexture(this); // remove this texture from the texture client + } + + delete(this); + } + return (count); +} + +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::GetDevice(IDirect3DDevice9** ppDevice) +{ + *ppDevice = m_D3Ddev; + return D3D_OK; +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); + return (m_D3Dtex->SetPrivateData(refguid, pData, SizeOfData, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); + return (m_D3Dtex->GetPrivateData(refguid, pData, pSizeOfData)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::FreePrivateData(REFGUID refguid) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->FreePrivateData(refguid)); + return (m_D3Dtex->FreePrivateData(refguid)); +} + +DWORD APIENTRY uMod_IDirect3DVolumeTexture9::SetPriority(DWORD PriorityNew) +{ + return (m_D3Dtex->SetPriority(PriorityNew)); +} + +DWORD APIENTRY uMod_IDirect3DVolumeTexture9::GetPriority() +{ + return (m_D3Dtex->GetPriority()); +} + +void APIENTRY uMod_IDirect3DVolumeTexture9::PreLoad() +{ + m_D3Dtex->PreLoad(); +} + +D3DRESOURCETYPE APIENTRY uMod_IDirect3DVolumeTexture9::GetType() +{ + return (m_D3Dtex->GetType()); +} + +DWORD APIENTRY uMod_IDirect3DVolumeTexture9::SetLOD(DWORD LODNew) +{ + return (m_D3Dtex->SetLOD(LODNew)); +} + +DWORD APIENTRY uMod_IDirect3DVolumeTexture9::GetLOD() +{ + return (m_D3Dtex->GetLOD()); +} + +DWORD APIENTRY uMod_IDirect3DVolumeTexture9::GetLevelCount() +{ + return (m_D3Dtex->GetLevelCount()); +} + +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::SetAutoGenFilterType(D3DTEXTUREFILTERTYPE FilterType) +{ + return (m_D3Dtex->SetAutoGenFilterType(FilterType)); +} + +D3DTEXTUREFILTERTYPE APIENTRY uMod_IDirect3DVolumeTexture9::GetAutoGenFilterType() +{ + return (m_D3Dtex->GetAutoGenFilterType()); +} + +void APIENTRY uMod_IDirect3DVolumeTexture9::GenerateMipSubLevels() +{ + m_D3Dtex->GenerateMipSubLevels(); +} + + + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::AddDirtyBox(CONST D3DBOX *pDirtyBox) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->AddDirtyBox(pDirtyBox)); + return (m_D3Dtex->AddDirtyBox(pDirtyBox)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::GetLevelDesc(UINT Level, D3DVOLUME_DESC *pDesc) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetLevelDesc(Level, pDesc)); + return (m_D3Dtex->GetLevelDesc(Level, pDesc)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::GetVolumeLevel(UINT Level, IDirect3DVolume9 **ppVolumeLevel) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->GetVolumeLevel(Level, ppVolumeLevel)); + return (m_D3Dtex->GetVolumeLevel(Level, ppVolumeLevel)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::LockBox(UINT Level, D3DLOCKED_BOX *pLockedVolume, CONST D3DBOX *pBox ,DWORD Flags) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->LockBox(Level, pLockedVolume, pBox, Flags)); + return (m_D3Dtex->LockBox(Level, pLockedVolume, pBox, Flags)); +} + +//this function yields for the non switched texture object +HRESULT APIENTRY uMod_IDirect3DVolumeTexture9::UnlockBox(UINT Level) +{ + if (CrossRef_D3Dtex!=NULL) return (CrossRef_D3Dtex->m_D3Dtex->UnlockBox(Level)); + return (m_D3Dtex->UnlockBox(Level)); +} + + +int uMod_IDirect3DVolumeTexture9::GetHash(MyTypeHash &hash) +{ + hash=0u; + if (FAKE) return (RETURN_BAD_ARGUMENT); + IDirect3DVolumeTexture9 *pTexture = m_D3Dtex; + if (CrossRef_D3Dtex!=NULL) pTexture = CrossRef_D3Dtex->m_D3Dtex; + + //IDirect3DVolume9 *pOffscreenSurface = NULL; + //IDirect3DVolumeTexture9 *pOffscreenTexture = NULL; + IDirect3DVolume9 *pResolvedSurface = NULL; + D3DLOCKED_BOX d3dlr; + D3DVOLUME_DESC desc; + + if (pTexture->GetLevelDesc(0, &desc)!=D3D_OK) //get the format and the size of the texture + { + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetLevelDesc \n"); + return (RETURN_GetLevelDesc_FAILED); + } + + Message("uMod_IDirect3DVolumeTexture9::GetHash() (%d %d %d) %d\n", desc.Width, desc.Height, desc.Depth, desc.Format); + +/* + if (desc.Pool==D3DPOOL_DEFAULT) //get the raw data of the texture + { + //Message("uMod_IDirect3DVolumeTexture9::GetHash() (D3DPOOL_DEFAULT)\n"); + + IDirect3DSurface9 *pSurfaceLevel_orig = NULL; + if (pTexture->GetSurfaceLevel( 0, &pSurfaceLevel_orig)!=D3D_OK) + { + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetSurfaceLevel 1 (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } +/* + if (desc.MultiSampleType != D3DMULTISAMPLE_NONE) + { + //Message("uMod_IDirect3DVolumeTexture9::GetHash() MultiSampleType\n"); + if (D3D_OK!=m_D3Ddev->CreateRenderTarget( desc.Width, desc.Height, desc.Format, D3DMULTISAMPLE_NONE, 0, FALSE, &pResolvedSurface, NULL )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: CreateRenderTarget (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + if (D3D_OK!=m_D3Ddev->StretchRect( pSurfaceLevel_orig, NULL, pResolvedSurface, NULL, D3DTEXF_NONE )) + { + pSurfaceLevel_orig->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: StretchRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + pSurfaceLevel_orig = pResolvedSurface; + } + */ +//CreateTexture(8, 8, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, (IDirect3DVolumeTexture9**) &SingleTexture, NULL) + /* + if (D3D_OK!=m_D3Ddev->CreateTexture( desc.Width, desc.Height, 1, 0, desc.Format, D3DPOOL_SYSTEMMEM, &pOffscreenTexture, NULL)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: CreateTexture (D3DPOOL_DEFAULT)\n"); + return (RETURN_TEXTURE_NOT_LOADED); + } + if (pOffscreenTexture->GetSurfaceLevel( 0, &pOffscreenSurface)!=D3D_OK) + { + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetSurfaceLevel 2 (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + + if (D3D_OK!=m_D3Ddev->GetRenderTargetData( pSurfaceLevel_orig, pOffscreenSurface)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + pOffscreenTexture->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetRenderTargetData (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + pSurfaceLevel_orig->Release(); + + if (pOffscreenSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + pOffscreenTexture->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: LockRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + */ +/* + if (D3D_OK!=m_D3Ddev->CreateOffscreenPlainSurface( desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &pOffscreenSurface, NULL)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: CreateOffscreenPlainSurface (D3DPOOL_DEFAULT)\n"); + return (RETURN_TEXTURE_NOT_LOADED); + } + + if (D3D_OK!=m_D3Ddev->GetRenderTargetData( pSurfaceLevel_orig, pOffscreenSurface)) + { + pSurfaceLevel_orig->Release(); + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetRenderTargetData (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + pSurfaceLevel_orig->Release(); + + if (pOffscreenSurface->LockRect( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + if (pResolvedSurface!=NULL) pResolvedSurface->Release(); + pOffscreenSurface->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: LockRect (D3DPOOL_DEFAULT)\n"); + return (RETURN_LockRect_FAILED); + } + } + else + */ + if (pTexture->LockBox( 0, &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: LockRect 1\n"); + if (pTexture->GetVolumeLevel(0, &pResolvedSurface)!=D3D_OK) + { + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: GetSurfaceLevel\n"); + return (RETURN_LockRect_FAILED); + } + if (pResolvedSurface->LockBox( &d3dlr, NULL, D3DLOCK_READONLY)!=D3D_OK) + { + pResolvedSurface->Release(); + Message("uMod_IDirect3DVolumeTexture9::GetHash() Failed: LockRect 2\n"); + return (RETURN_LockRect_FAILED); + } + } + + int size = (GetBitsFromFormat( desc.Format) * desc.Width*desc.Height*desc.Depth)/8; + + hash = GetCRC32( (char*) d3dlr.pBits, size); //calculate the crc32 of the texture + + + if (pResolvedSurface!=NULL) + { + pResolvedSurface->UnlockBox(); + pResolvedSurface->Release(); + } + else pTexture->UnlockBox(0); + + Message("uMod_IDirect3DVolumeTexture9::GetHash() %#lX (%d %d) %d = %d\n", hash, desc.Width, desc.Height, desc.Format, size); + return (RETURN_OK); +} diff --git a/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h b/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h new file mode 100644 index 0000000..0c2c81a --- /dev/null +++ b/uMod2/uMod_DX9/uMod_IDirect3DVolumeTexture9.h @@ -0,0 +1,125 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +/* + * + * BIG THANKS TO Matthew L (Azorbix) + * (Direct3D StarterKit v3.0) + * + */ + + +#ifndef uMod_IDirect3DVolumeTexture9_H +#define uMod_IDirect3DVolumeTexture9_H + +#include +#include + +#include "uMod_Defines.h" + + + +interface uMod_IDirect3DVolumeTexture9 : public IDirect3DVolumeTexture9 +{ + uMod_IDirect3DVolumeTexture9(IDirect3DVolumeTexture9 **ppTex, IDirect3DDevice9 *pIDirect3DDevice9) + { + m_D3Dtex = *ppTex; //Texture which will be displayed and will be passed to the game + m_D3Ddev = pIDirect3DDevice9; //device pointer + CrossRef_D3Dtex = NULL; //cross reference + // fake texture: store the pointer to the original uMod_IDirect3DVolumeTexture9 object, needed if a fake texture is unselected + // original texture: stores the pointer to the fake texture object, is needed if original texture is deleted, + // thus the fake texture can also be deleted + Reference = -1; //need for fast deleting + Hash = 0u; + FAKE = false; + } + + // callback interface + IDirect3DVolumeTexture9 *m_D3Dtex; + uMod_IDirect3DVolumeTexture9 *CrossRef_D3Dtex; + IDirect3DDevice9 *m_D3Ddev; + int Reference; + MyTypeHash Hash; + bool FAKE; + + // original interface + STDMETHOD(QueryInterface) (REFIID riid, void** ppvObj); + STDMETHOD_(ULONG,AddRef)(); + STDMETHOD_(ULONG,Release)(); + STDMETHOD(GetDevice)(IDirect3DDevice9** ppDevice); + STDMETHOD(SetPrivateData)(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags); + STDMETHOD(GetPrivateData)(REFGUID refguid,void* pData,DWORD* pSizeOfData); + STDMETHOD(FreePrivateData)(REFGUID refguid); + STDMETHOD_(DWORD, SetPriority)(DWORD PriorityNew); + STDMETHOD_(DWORD, GetPriority)(); + STDMETHOD_(void, PreLoad)(); + STDMETHOD_(D3DRESOURCETYPE, GetType)(); + STDMETHOD_(DWORD, SetLOD)(DWORD LODNew); + STDMETHOD_(DWORD, GetLOD)(); + STDMETHOD_(DWORD, GetLevelCount)(); + STDMETHOD(SetAutoGenFilterType)(D3DTEXTUREFILTERTYPE FilterType); + STDMETHOD_(D3DTEXTUREFILTERTYPE, GetAutoGenFilterType)(); + STDMETHOD_(void, GenerateMipSubLevels)(); + STDMETHOD(AddDirtyBox)(CONST D3DBOX *pDirtyBox); + STDMETHOD(GetLevelDesc)(UINT Level, D3DVOLUME_DESC *pDesc); + STDMETHOD(GetVolumeLevel)(UINT Level, IDirect3DVolume9 **ppVolumeLevel); + STDMETHOD(LockBox)(UINT Level, D3DLOCKED_BOX *pLockedVolume, CONST D3DBOX *pBox, DWORD Flags); + STDMETHOD(UnlockBox)(UINT Level); + + + int GetHash(MyTypeHash &hash); +}; + + + +inline void UnswitchTextures(uMod_IDirect3DVolumeTexture9 *pTexture) +{ + uMod_IDirect3DVolumeTexture9* CrossRef = pTexture->CrossRef_D3Dtex; + if (CrossRef!=NULL) + { + // switch textures back + IDirect3DVolumeTexture9* cpy = pTexture->m_D3Dtex; + pTexture->m_D3Dtex = CrossRef->m_D3Dtex; + CrossRef->m_D3Dtex = cpy; + + // cancel the link + CrossRef->CrossRef_D3Dtex = NULL; + pTexture->CrossRef_D3Dtex = NULL; + } +} + +inline int SwitchTextures( uMod_IDirect3DVolumeTexture9 *pTexture1, uMod_IDirect3DVolumeTexture9 *pTexture2) +{ + if (pTexture1->m_D3Ddev == pTexture2->m_D3Ddev && pTexture1->CrossRef_D3Dtex == NULL && pTexture2->CrossRef_D3Dtex == NULL) + { + // make cross reference + pTexture1->CrossRef_D3Dtex = pTexture2; + pTexture2->CrossRef_D3Dtex = pTexture1; + + // switch textures + IDirect3DVolumeTexture9* cpy = pTexture2->m_D3Dtex; + pTexture2->m_D3Dtex = pTexture1->m_D3Dtex; + pTexture1->m_D3Dtex = cpy; + return (RETURN_OK); + } + else return (RETURN_TEXTURE_NOT_SWITCHED); +} + + +#endif diff --git a/uMod2/uMod_DX9/uMod_Main.h b/uMod2/uMod_DX9/uMod_Main.h new file mode 100644 index 0000000..6655982 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_Main.h @@ -0,0 +1,66 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_MAIN_H_ +#define uMod_MAIN_H_ + +#define WINVER _WIN32_WINNT_WINXP +#define _WIN32_WINNT _WIN32_WINNT_WINXP +#define _WIN32_WINDOWS _WIN32_WINNT_WINXP +#define NTDDI_VERSION NTDDI_WINXP +//#define NTDDI_LONGHORN NTDDI_WINXP +#define WIN32_LEAN_AND_MEAN + + +#include + +#include +#include + +#include +#include + + + + +#include "../uMod_GlobalDefines.h" +#include "../uMod_Error.h" +#include "uMod_Defines.h" +#include "uMod_DX9_dll.h" +#include "uMod_TextureFunction.h" + +#include "uMod_IDirect3D9.h" +#include "uMod_IDirect3D9Ex.h" + +#include "uMod_IDirect3DDevice9.h" +#include "uMod_IDirect3DDevice9Ex.h" + +#include "uMod_IDirect3DCubeTexture9.h" +#include "uMod_IDirect3DTexture9.h" +#include "uMod_IDirect3DVolumeTexture9.h" + +#include "uMod_ArrayHandler.h" +#include "uMod_TextureServer.h" +#include "uMod_TextureClient.h" + + +extern unsigned int gl_ErrorState; + +#endif diff --git a/uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp b/uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp new file mode 100644 index 0000000..cf493f9 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_TextureClient_DX9.cpp @@ -0,0 +1,859 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + +uMod_TextureClient::uMod_TextureClient(uMod_TextureServer* server, IDirect3DDevice9* device) +{ + Message("uMod_TextureClient::uMod_TextureClient(void): %lu\n", this); + Server = server; + D3D9Device = device; + BoolSaveAllTextures = false; + BoolSaveSingleTexture = false; + KeyBack = 0; + KeySave = 0; + KeyNext = 0; + SavePath[0]=0; + GameName[0]=0; + + NumberToMod = 0; + FileToMod = NULL; + + if (Server!=NULL) + { + if (Server->AddClient( this, &FileToMod, &NumberToMod)) + { + Server=NULL; + NumberToMod = 0; + FileToMod = NULL; + } + else + { + for (int i=0; iRemoveClient(this); + + if (Mutex!=NULL) CloseHandle(Mutex); + + if (Update!=NULL) delete [] Update; + if (FileToMod!=NULL) + { + for (int i=0; iQueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + +int uMod_TextureClient::AddTexture( uMod_IDirect3DVolumeTexture9* pTexture) +{ + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( Volume: %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalVolumeTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalVolumeTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + +int uMod_TextureClient::AddTexture( uMod_IDirect3DCubeTexture9* pTexture) +{ + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( Cube: %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalCubeTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalCubeTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + + +int uMod_TextureClient::CheckAgainNonAdded(void) +{ + Message("uMod_TextureClient::CheckAgainNonAdded( %u, %u, %u): %lu\n", NonAdded_OriginalTextures.GetNumber(), + NonAdded_OriginalVolumeTextures.GetNumber(), NonAdded_OriginalCubeTextures.GetNumber(), this); + + Bool_CheckAgainNonAdded = false; + + int num = NonAdded_OriginalTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DTexture9* pTexture = NonAdded_OriginalTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalTextures.Remove(pTexture); + OriginalTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + + num = NonAdded_OriginalVolumeTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DVolumeTexture9* pTexture = NonAdded_OriginalVolumeTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalVolumeTextures.Remove(pTexture); + OriginalVolumeTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + + num = NonAdded_OriginalCubeTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DCubeTexture9* pTexture = NonAdded_OriginalCubeTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalCubeTextures.Remove(pTexture); + OriginalCubeTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + Message("uMod_TextureClient::CheckAgainNonAdded() END: %lu\n", this); + return (RETURN_OK); +} + +int uMod_TextureClient::RemoveTexture( uMod_IDirect3DTexture9* pTexture) // is called from a texture, if it is finally released +{ + Message("uMod_TextureClient::RemoveTexture( %lu, %#lX): %lu\n", pTexture, pTexture->Hash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refHash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refHash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refQueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) pTexture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleTexture(); //this texture must no be added twice + else pTexture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleTexture(); //this texture must no be added twice + + if (pTexture!=NULL) UnswitchTextures(pTexture); + } + BoolSaveSingleTexture = val; + return (RETURN_OK); +} + + +int uMod_TextureClient::SetSaveDirectory( wchar_t *dir) +{ + Message("uMod_TextureClient::SetSaveDirectory( %ls): %lu\n", dir, this); + int i = 0; + for (i=0; iHash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_T_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\T_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + +int uMod_TextureClient::SaveTexture(uMod_IDirect3DVolumeTexture9* pTexture) +{ + if (pTexture==NULL) return (RETURN_BAD_ARGUMENT); + if (SavePath[0]==0) {Message("uMod_TextureClient::SaveTexture( %#lX, %lu): %lu, SavePath not set\n", pTexture->Hash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_V_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\V_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + +int uMod_TextureClient::SaveTexture(uMod_IDirect3DCubeTexture9* pTexture) +{ + if (pTexture==NULL) return (RETURN_BAD_ARGUMENT); + if (SavePath[0]==0) {Message("uMod_TextureClient::SaveTexture( %#lX, %lu): %lu, SavePath not set\n", pTexture->Hash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_C_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\C_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + + + + +int uMod_TextureClient::AddUpdate(TextureFileStruct* update, int number) //client must delete the update array +{ + Message("AddUpdate( %lu, %d): %lu\n", update, number, this); + if (int ret = LockMutex()) {gl_ErrorState |= uMod_ERROR_TEXTURE; return (ret);} + if (Update!=NULL) delete [] Update; + Update = update; + NumberOfUpdate = number; + return (UnlockMutex()); +} + + + +int uMod_TextureClient::MergeUpdate(void) +{ + if (NumberOfUpdate<0) {return (RETURN_OK);} + if (int ret = LockMutex()) {gl_ErrorState |= uMod_ERROR_TEXTURE ; return (ret);} + + Message("uMod_TextureClient::MergeUpdate(): %lu\n", this); + + for (int i=0; i0) to_lookup = new int[NumberOfUpdate]; + int num_to_lookup = 0; + + /* + * FileToMod contains the old files (textures) which should replace the target textures (if they are loaded by the game) + * Update contains the new files (textures) which should replace the target textures (if they are loaded by the game) + * + * Both arrays (FileToMod and Update) are sorted according to their hash values. + * + * First we go through both arrays linearly and + * 1) take over the old entry if the hash is the same, + * 2) release old fake texture (if target texture exist and is not in the Update) + * 3) or mark newly added fake texture (if they are not in FileToMod) + */ + + while (pos_old Update[pos_new].Hash) // this fake texture is new + { + to_lookup[num_to_lookup++] = pos_new++; // keep this fake texture in mind, we must search later for it through all original textures + // we increase only the new counter by one + } + else if (FileToMod[pos_old].Hash < Update[pos_new].Hash) // this fake texture is not in the update + { + for (int i=FileToMod[pos_old].NumberOfTextures-1; i>=0; i--) FileToMod[pos_old].Textures[i]->Release(); // we release the fake textures + if (FileToMod[pos_old].Textures!=NULL) delete [] FileToMod[pos_old].Textures; // we delete the memory + FileToMod[pos_old].NumberOfTextures = 0; + FileToMod[pos_old].Textures = NULL; + + pos_old++; // we increase only the old counter by one + } + else // the hash value is the same, thus this texture is in the array FileToMod as well as in the array Update + { + if (Update[pos_new].ForceReload) + { + if (FileToMod[pos_old].NumberOfTextures>0) + { + Update[pos_new].Textures = new IDirect3DBaseTexture9*[FileToMod[pos_old].NumberOfTextures]; + } + for (int i=0; iQueryInterface( IID_IDirect3D9, (void**)&base_texture); + switch (ret) + { + case 0x01000000L: + { + uMod_IDirect3DTexture9 *pTexture = (uMod_IDirect3DTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + case 0x01000001L: + { + uMod_IDirect3DVolumeTexture9 *pTexture = (uMod_IDirect3DVolumeTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DVolumeTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DVolumeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + case 0x01000002L: + { + uMod_IDirect3DCubeTexture9 *pTexture = (uMod_IDirect3DCubeTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DCubeTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DCubeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + default: + break; // this is no fake texture and QueryInterface failed, because IDirect3DBaseTexture9 object cannot be a IDirect3D9 object ;) + } + } + } + else // the texture might be loaded or not + { + Update[pos_new].NumberOfTextures = FileToMod[pos_old].NumberOfTextures; + Update[pos_new].Textures = FileToMod[pos_old].Textures; + FileToMod[pos_old].NumberOfTextures = 0; + FileToMod[pos_old].Textures = NULL; + } + // we increase both counters by one + pos_old++; + pos_new++; + } + } + + while (pos_old=0; i--) FileToMod[pos_old].Textures[i]->Release(); // we release the fake textures + //for (int i=0; iRelease(); // we release the fake textures + if (FileToMod[pos_old].Textures!=NULL) delete [] FileToMod[pos_old].Textures; // we delete the memory + FileToMod[pos_old].Textures = NULL; + pos_old++; + } + while (pos_new0) + { + uMod_IDirect3DTexture9* single_texture; + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) single_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleTexture(); //this texture must no be added twice + else single_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleTexture(); //this texture must no be added twice + + int num = OriginalTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalTextures[i]->CrossRef_D3Dtex==single_texture) + { + UnswitchTextures(OriginalTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalTextures[i], num_to_lookup, to_lookup); + } + + uMod_IDirect3DVolumeTexture9 *single_volume_texture; + if (ret == 0x01000000L) single_volume_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleVolumeTexture(); //this texture must no be added twice + else single_volume_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleVolumeTexture(); //this texture must no be added twice + num = OriginalVolumeTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalVolumeTextures[i]->CrossRef_D3Dtex==single_volume_texture) + { + UnswitchTextures(OriginalVolumeTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalVolumeTextures[i], num_to_lookup, to_lookup); + } + + uMod_IDirect3DCubeTexture9 *single_cube_texture; + if (ret == 0x01000000L) single_cube_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleCubeTexture(); //this texture must no be added twice + else single_cube_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleCubeTexture(); //this texture must no be added twice + num = OriginalCubeTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalCubeTextures[i]->CrossRef_D3Dtex==single_cube_texture) + { + UnswitchTextures(OriginalCubeTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalCubeTextures[i], num_to_lookup, to_lookup); + } + } + + + + if (to_lookup != NULL) delete [] to_lookup; + + Message("uMod_TextureClient::MergeUpdate() END: %lu\n", this); + + CheckAgainNonAdded(); + return (UnlockMutex()); +} + + + +int uMod_TextureClient::LockMutex(void) +{ + if (( gl_ErrorState & (uMod_ERROR_FATAL | uMod_ERROR_MUTEX) )) return (RETURN_NO_MUTEX); + if (WAIT_OBJECT_0!=WaitForSingleObject( Mutex, 100)) return (RETURN_MUTEX_LOCK); //waiting 100ms, to wait infinite pass INFINITE + return (RETURN_OK); +} + +int uMod_TextureClient::UnlockMutex(void) +{ + if (ReleaseMutex(Mutex)==0) return (RETURN_MUTEX_UNLOCK); + return (RETURN_OK); +} + + + + + +int uMod_TextureClient::LookUpToMod( MyTypeHash hash, int num_index_list, int *index_list) +{ + if(NumberToMod>0) + { + if (index_list==NULL || num_index_list==0) + { + if (hashFileToMod[NumberToMod-1].Hash) return (-1); + int pos = NumberToMod/2; + int begin = 0; + int end = NumberToMod-1; + + // We look in the middle of the interval and each step we halve the interval, + // unless we find the texture or the size of the interval is less than 3. + // Note: contradicting to normal C-code here the interval includes the index "begin" and "end"! + while (begin+1 FileToMod[pos].Hash) // the new interval is the right half of the actual interval + { + begin = pos+1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else if (hash < FileToMod[pos].Hash) // the new interval is the left half of the actual interval + { + end = pos-1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else {return (pos); break;} // we hit the correct hash + } + for ( pos=begin; pos<=end; pos++) if (FileToMod[pos].Hash==hash) return (pos); + } + else + { + if (hashFileToMod[index_list[num_index_list-1]].Hash) return (-1); + int pos = num_index_list/2; + int begin = 0; + int end = num_index_list-1; + + // We look in the middle of the interval and each step we halve the interval, + // unless we find the texture or the size of the interval is less than 3. + // Note: contradicting to normal C-code here the interval includes the index "begin" and "end"! + while (begin+1 FileToMod[index_list[pos]].Hash) // the new interval is the right half of the actual interval + { + begin = pos+1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else if (hash < FileToMod[index_list[pos]].Hash) // the new interval is the left half of the actual interval + { + end = pos-1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else {return (index_list[pos]); break;} // we hit the correct hash + } + for ( pos=begin; pos<=end; pos++) if (FileToMod[index_list[pos]].Hash==hash) return (index_list[pos]); + } + } + return (-1); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DVolumeTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( Volume %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DVolumeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DCubeTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( Cube %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DCubeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + + + + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DVolumeTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( Volume %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateVolumeTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DVolumeTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateVolumeTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DVolumeTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( Volume %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DCubeTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( Cube %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateCubeTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DCubeTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateCubeTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DCubeTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( Cube %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + + + + diff --git a/uMod2/uMod_DX9/uMod_TextureClient_DX9.h b/uMod2/uMod_DX9/uMod_TextureClient_DX9.h new file mode 100644 index 0000000..1d532bf --- /dev/null +++ b/uMod2/uMod_DX9/uMod_TextureClient_DX9.h @@ -0,0 +1,132 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_TEXTUREHANDLER_HPP +#define uMod_TEXTUREHANDLER_HPP + +#include "uMod_IDirect3DTexture9.h" +#include "uMod_IDirect3DDevice9.h" +#include "..\uMod_Error.h" + + +class uMod_TextureServer; + +/* + * An object of this class is owned by each d3d9 device. + * functions called by the Server are called from the server thread instance. + * All other functions are called from the render thread instance of the game itself. + */ + +class uMod_TextureClient +{ +public: + uMod_TextureClient(uMod_TextureServer* server, IDirect3DDevice9* device); + ~uMod_TextureClient(void); + + int AddTexture( uMod_IDirect3DTexture9* tex); //called from uMod_IDirect3DDevice9::CreateTexture(...) or uMod_IDirect3DDevice9::BeginScene() + int AddTexture( uMod_IDirect3DVolumeTexture9* tex); //called from uMod_IDirect3DVolumeTexture9::CreateTexture(...) or uMod_IDirect3DDevice9::BeginScene() + int AddTexture( uMod_IDirect3DCubeTexture9* tex); //called from uMod_IDirect3DCubeTexture9::CreateTexture(...) or uMod_IDirect3DDevice9::BeginScene() + + int RemoveTexture( uMod_IDirect3DTexture9* tex); //called from uMod_IDirect3DTexture9::Release() + int RemoveTexture( uMod_IDirect3DVolumeTexture9* tex); //called from uMod_IDirect3DVolumeTexture9::Release() + int RemoveTexture( uMod_IDirect3DCubeTexture9* tex); //called from uMod_IDirect3DCubeTexture9::Release() + + int SaveAllTextures(bool val); //called from the Server + int SaveSingleTexture(bool val); //called from the Server + + int SetSaveDirectory( wchar_t *dir); //called from the Server + int SetGameName( wchar_t *dir); //called from the Server + + int SaveTexture(uMod_IDirect3DTexture9* pTexture); //called from uMod_IDirect3DDevice9::BeginScene() (save button) or from AddTexture(...) (SaveAllTextures) + int SaveTexture(uMod_IDirect3DVolumeTexture9* pTexture); //called from uMod_IDirect3DDevice9::BeginScene() (save button) or from AddTexture(...) (SaveAllTextures) + int SaveTexture(uMod_IDirect3DCubeTexture9* pTexture); //called from uMod_IDirect3DDevice9::BeginScene() (save button) or from AddTexture(...) (SaveAllTextures) + + + + int SetKeyBack( int key) {if (key>0) KeyBack = key; return (RETURN_OK);} //called from the Server + int SetKeySave( int key) {if (key>0) KeySave = key; return (RETURN_OK);} //called from the Server + int SetKeyNext( int key) {if (key>0) KeyNext = key; return (RETURN_OK);} //called from the Server + + int SetFontColour( DWORD r, DWORD g, DWORD b) {FontColour = D3DCOLOR_ARGB(255, r,g,b); return (RETURN_OK);} //called from the Server + int SetTextureColour( DWORD r, DWORD g, DWORD b) {TextureColour = D3DCOLOR_ARGB(255, r,g,b); return (RETURN_OK);} //called from the Server + + + int AddUpdate(TextureFileStruct* update, int number); //called from the Server, client object must delete update array + int MergeUpdate(void); //called from uMod_IDirect3DDevice9::BeginScene() + + + + int LookUpToMod( uMod_IDirect3DTexture9* pTexture, int num_index_list=0, int *index_list=NULL); // called at the end AddTexture(...) and from Device->UpdateTexture(...) + int LookUpToMod( uMod_IDirect3DVolumeTexture9* pTexture, int num_index_list=0, int *index_list=NULL); // called at the end AddTexture(...) and from Device->UpdateTexture(...) + int LookUpToMod( uMod_IDirect3DCubeTexture9* pTexture, int num_index_list=0, int *index_list=NULL); // called at the end AddTexture(...) and from Device->UpdateTexture(...) + + uMod_TextureHandler OriginalTextures; // stores the pointer to the uMod_IDirect3DTexture9 objects created by the game + uMod_TextureHandler OriginalVolumeTextures; // stores the pointer to the uMod_IDirect3DVolumeTexture9 objects created by the game + uMod_TextureHandler OriginalCubeTextures; // stores the pointer to the uMod_IDirect3DCubeTexture9 objects created by the game + + + // if the has could not be calculated for a texture it is not considered in the original texture list, + // but it is now added into the following lists and we try to calculate the hash once again later + int CheckAgainNonAdded(void); + bool Bool_CheckAgainNonAdded; + uMod_TextureHandler NonAdded_OriginalTextures; // stores the pointer to the uMod_IDirect3DTexture9 objects created by the game + uMod_TextureHandler NonAdded_OriginalVolumeTextures; // stores the pointer to the uMod_IDirect3DVolumeTexture9 objects created by the game + uMod_TextureHandler NonAdded_OriginalCubeTextures; // stores the pointer to the uMod_IDirect3DCubeTexture9 objects created by the game + + bool BoolSaveAllTextures; + bool BoolSaveSingleTexture; + int KeyBack; + int KeySave; + int KeyNext; + + D3DCOLOR FontColour; + D3DCOLOR TextureColour; + +private: + uMod_TextureServer* Server; + IDirect3DDevice9* D3D9Device; + wchar_t SavePath[MAX_PATH]; + wchar_t GameName[MAX_PATH]; + + TextureFileStruct* Update; + int NumberOfUpdate; + + int LockMutex(); + int UnlockMutex(); + HANDLE Mutex; + + int NumberToMod; // number of texture to be modded + TextureFileStruct* FileToMod; // array which stores the file in memory and the hash of each texture to be modded + + + int LookUpToMod( MyTypeHash hash, int num_index_list, int *index_list); // called from LookUpToMod(...); + int LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DTexture9 **ppTexture); // called if a target texture is found + int LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DVolumeTexture9 **ppTexture); // called if a target texture is found + int LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DCubeTexture9 **ppTexture); // called if a target texture is found + + // and the corresponding fake texture should be loaded + + //MyTypeHash GetHash(unsigned char *str, int len); + //unsigned int GetCRC32(char *pcDatabuf, unsigned int ulDatalen); +}; + + + +#endif /* uMod_TEXTUREHANDLER_HPP_ */ diff --git a/uMod2/uMod_DX9/uMod_TextureFunction.cpp b/uMod2/uMod_DX9/uMod_TextureFunction.cpp new file mode 100644 index 0000000..24a009a --- /dev/null +++ b/uMod2/uMod_DX9/uMod_TextureFunction.cpp @@ -0,0 +1,62 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +#include "uMod_Main.h" + +/* +MyTypeHash GetHash(unsigned char *str, int len) // estimate the hash +{ + MyTypeHash hash = 0; + for (int i=0; i>=1) + { + crc = (crc >> 1) ^ (((crc ^ data) & 1) ? CRC32POLY : 0); + } + } + return (crc); +} + diff --git a/uMod2/uMod_DX9/uMod_TextureFunction.h b/uMod2/uMod_DX9/uMod_TextureFunction.h new file mode 100644 index 0000000..c371a34 --- /dev/null +++ b/uMod2/uMod_DX9/uMod_TextureFunction.h @@ -0,0 +1,147 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ +#ifndef uMod_TEXTUREFUNCTION_H_ +#define uMod_TEXTUREFUNCTION_H_ + + +unsigned int GetCRC32( char *pcDatabuf, unsigned int ulDatalen); +/* + case D3DFMT_MULTI2_ARGB8: + case D3DFMT_VERTEXDATA: + */ +inline int GetBitsFromFormat(D3DFORMAT format) +{ + switch(format) //switch trough the formats to calculate the size of the raw data + { + case D3DFMT_A1: // 1-bit monochrome. + { + return (1); + break; + } + + case D3DFMT_R3G3B2: // 8-bit RGB texture format using 3 bits for red, 3 bits for green, and 2 bits for blue. + case D3DFMT_A8: // 8-bit alpha only. + case D3DFMT_A8P8: // 8-bit color indexed with 8 bits of alpha. + case D3DFMT_P8: // 8-bit color indexed. + case D3DFMT_L8: // 8-bit luminance only. + case D3DFMT_A4L4: // 8-bit using 4 bits each for alpha and luminance. + case D3DFMT_FORCE_DWORD: + case D3DFMT_S8_LOCKABLE: // A lockable 8-bit stencil buffer. + { + return (8); + break; + } + + case D3DFMT_D16_LOCKABLE: //16-bit z-buffer bit depth. + case D3DFMT_D15S1: // 16-bit z-buffer bit depth where 15 bits are reserved for the depth channel and 1 bit is reserved for the stencil channel. + case D3DFMT_L6V5U5: // 16-bit bump-map format with luminance using 6 bits for luminance, and 5 bits each for v and u. + case D3DFMT_V8U8: // 16-bit bump-map format using 8 bits each for u and v data. + case D3DFMT_CxV8U8: // 16-bit normal compression format. The texture sampler computes the C channel from: C = sqrt(1 - U2 - V2). + case D3DFMT_R5G6B5: // 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for blue. + case D3DFMT_X1R5G5B5: // 16-bit pixel format where 5 bits are reserved for each color. + case D3DFMT_A1R5G5B5: // 16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha. + case D3DFMT_A4R4G4B4: // 16-bit ARGB pixel format with 4 bits for each channel. + case D3DFMT_A8R3G3B2: // 16-bit ARGB texture format using 8 bits for alpha, 3 bits each for red and green, and 2 bits for blue. + case D3DFMT_X4R4G4B4: // 16-bit RGB pixel format using 4 bits for each color. + case D3DFMT_L16: // 16-bit luminance only. + case D3DFMT_R16F: // 16-bit float format using 16 bits for the red channel. + case D3DFMT_A8L8: // 16-bit using 8 bits each for alpha and luminance. + case D3DFMT_D16: // 16-bit z-buffer bit depth. + case D3DFMT_INDEX16: // 16-bit index buffer bit depth. + case D3DFMT_G8R8_G8B8: // ?? + case D3DFMT_R8G8_B8G8: // ?? + case D3DFMT_UYVY: // ?? + case D3DFMT_YUY2: // ?? + { + return (16); + break; + } + + + case D3DFMT_R8G8B8: //24-bit RGB pixel format with 8 bits per channel. + { + return (24); + break; + } + + case D3DFMT_R32F: // 32-bit float format using 32 bits for the red channel. + case D3DFMT_X8L8V8U8: // 32-bit bump-map format with luminance using 8 bits for each channel. + case D3DFMT_A2W10V10U10: // 32-bit bump-map format using 2 bits for alpha and 10 bits each for w, v, and u. + case D3DFMT_Q8W8V8U8: // 32-bit bump-map format using 8 bits for each channel. + case D3DFMT_V16U16: // 32-bit bump-map format using 16 bits for each channel. + case D3DFMT_A8R8G8B8: // 32-bit ARGB pixel format with alpha, using 8 bits per channel. + case D3DFMT_X8R8G8B8: // 32-bit RGB pixel format, where 8 bits are reserved for each color. + case D3DFMT_A2B10G10R10: // 32-bit pixel format using 10 bits for each color and 2 bits for alpha. + case D3DFMT_A8B8G8R8: // 32-bit ARGB pixel format with alpha, using 8 bits per channel. + case D3DFMT_X8B8G8R8: // 32-bit RGB pixel format, where 8 bits are reserved for each color. + case D3DFMT_G16R16: // 32-bit pixel format using 16 bits each for green and red. + case D3DFMT_G16R16F: // 32-bit float format using 16 bits for the red channel and 16 bits for the green channel. + case D3DFMT_A2R10G10B10: // 32-bit pixel format using 10 bits each for red, green, and blue, and 2 bits for alpha. + case D3DFMT_D32: // 32-bit z-buffer bit depth. + case D3DFMT_D24S8: // 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel. + case D3DFMT_D24X8: //32-bit z-buffer bit depth using 24 bits for the depth channel. + case D3DFMT_D24X4S4: // 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel. + case D3DFMT_D32F_LOCKABLE: // A lockable format where the depth value is represented as a standard IEEE floating-point number. + case D3DFMT_D24FS8: // A non-lockable format that contains 24 bits of depth (in a 24-bit floating point format - 20e4) and 8 bits of stencil. + case D3DFMT_D32_LOCKABLE: // A lockable 32-bit depth buffer. + case D3DFMT_INDEX32: // 32-bit index buffer bit depth. + //case : // + //case : // + //case : // + //case : // + { + return (32); + break; + } + + case D3DFMT_G32R32F: // 64-bit float format using 32 bits for the red channel and 32 bits for the green channel. + case D3DFMT_Q16W16V16U16: // 64-bit bump-map format using 16 bits for each component. + case D3DFMT_A16B16G16R16: // 64-bit pixel format using 16 bits for each component. + case D3DFMT_A16B16G16R16F: // 64-bit float format using 16 bits for the each channel (alpha, blue, green, red). + { + return (64); + break; + } + + case D3DFMT_A32B32G32R32F: // 128-bit float format using 32 bits for the each channel (alpha, blue, green, red). + { + return (128); + break; + } + case D3DFMT_DXT2: + case D3DFMT_DXT3: + case D3DFMT_DXT4: + case D3DFMT_DXT5: + { + return (8); + break; + } + case D3DFMT_DXT1: + { + return (4); + break; + } + default: //compressed formats + { + return (4); + break; + } + } +} + +#endif /* uMod_TEXTUREFUNCTION_H_ */ diff --git a/uMod2/uMod_DXMain/uMod_TextureClient.cpp b/uMod2/uMod_DXMain/uMod_TextureClient.cpp new file mode 100644 index 0000000..cf493f9 --- /dev/null +++ b/uMod2/uMod_DXMain/uMod_TextureClient.cpp @@ -0,0 +1,859 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + +uMod_TextureClient::uMod_TextureClient(uMod_TextureServer* server, IDirect3DDevice9* device) +{ + Message("uMod_TextureClient::uMod_TextureClient(void): %lu\n", this); + Server = server; + D3D9Device = device; + BoolSaveAllTextures = false; + BoolSaveSingleTexture = false; + KeyBack = 0; + KeySave = 0; + KeyNext = 0; + SavePath[0]=0; + GameName[0]=0; + + NumberToMod = 0; + FileToMod = NULL; + + if (Server!=NULL) + { + if (Server->AddClient( this, &FileToMod, &NumberToMod)) + { + Server=NULL; + NumberToMod = 0; + FileToMod = NULL; + } + else + { + for (int i=0; iRemoveClient(this); + + if (Mutex!=NULL) CloseHandle(Mutex); + + if (Update!=NULL) delete [] Update; + if (FileToMod!=NULL) + { + for (int i=0; iQueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + +int uMod_TextureClient::AddTexture( uMod_IDirect3DVolumeTexture9* pTexture) +{ + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( Volume: %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalVolumeTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalVolumeTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + +int uMod_TextureClient::AddTexture( uMod_IDirect3DCubeTexture9* pTexture) +{ + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + + if (pTexture->FAKE) return (RETURN_OK); // this is a fake texture + + Message("uMod_TextureClient::AddTexture( Cube: %lu): %lu (thread: %lu)\n", pTexture, this, GetCurrentThreadId()); + + MyTypeHash hash; + if (int ret = pTexture->GetHash( hash)) + { + Bool_CheckAgainNonAdded = true; + NonAdded_OriginalCubeTextures.Add( pTexture); + return (ret); + } + + pTexture->Hash = hash; + + if (BoolSaveAllTextures) SaveTexture(pTexture); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + + OriginalCubeTextures.Add( pTexture); // add the texture to the list of original texture + + return (LookUpToMod(pTexture)); // check if this texture should be modded +} + + +int uMod_TextureClient::CheckAgainNonAdded(void) +{ + Message("uMod_TextureClient::CheckAgainNonAdded( %u, %u, %u): %lu\n", NonAdded_OriginalTextures.GetNumber(), + NonAdded_OriginalVolumeTextures.GetNumber(), NonAdded_OriginalCubeTextures.GetNumber(), this); + + Bool_CheckAgainNonAdded = false; + + int num = NonAdded_OriginalTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DTexture9* pTexture = NonAdded_OriginalTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalTextures.Remove(pTexture); + OriginalTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + + num = NonAdded_OriginalVolumeTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DVolumeTexture9* pTexture = NonAdded_OriginalVolumeTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalVolumeTextures.Remove(pTexture); + OriginalVolumeTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + + num = NonAdded_OriginalCubeTextures.GetNumber(); + for (int i=num-1; i>=0; i--) + { + uMod_IDirect3DCubeTexture9* pTexture = NonAdded_OriginalCubeTextures[i]; + + MyTypeHash hash; + if (pTexture->GetHash( hash) == 0) + { + NonAdded_OriginalCubeTextures.Remove(pTexture); + OriginalCubeTextures.Add( pTexture); // add the texture to the list of original texture + LookUpToMod(pTexture); // check if this texture should be modded + } + } + Message("uMod_TextureClient::CheckAgainNonAdded() END: %lu\n", this); + return (RETURN_OK); +} + +int uMod_TextureClient::RemoveTexture( uMod_IDirect3DTexture9* pTexture) // is called from a texture, if it is finally released +{ + Message("uMod_TextureClient::RemoveTexture( %lu, %#lX): %lu\n", pTexture, pTexture->Hash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refHash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refHash, this); + + if (gl_ErrorState & uMod_ERROR_FATAL) return (RETURN_FATAL_ERROR); + if (pTexture->FAKE) + { + // we need to set the corresponding FileToMod[X].pTexture to NULL, to avoid a link to a non existing texture object + int ref = pTexture->Reference; + if (ref>=0 && refQueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) pTexture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleTexture(); //this texture must no be added twice + else pTexture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleTexture(); //this texture must no be added twice + + if (pTexture!=NULL) UnswitchTextures(pTexture); + } + BoolSaveSingleTexture = val; + return (RETURN_OK); +} + + +int uMod_TextureClient::SetSaveDirectory( wchar_t *dir) +{ + Message("uMod_TextureClient::SetSaveDirectory( %ls): %lu\n", dir, this); + int i = 0; + for (i=0; iHash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_T_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\T_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + +int uMod_TextureClient::SaveTexture(uMod_IDirect3DVolumeTexture9* pTexture) +{ + if (pTexture==NULL) return (RETURN_BAD_ARGUMENT); + if (SavePath[0]==0) {Message("uMod_TextureClient::SaveTexture( %#lX, %lu): %lu, SavePath not set\n", pTexture->Hash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_V_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\V_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + +int uMod_TextureClient::SaveTexture(uMod_IDirect3DCubeTexture9* pTexture) +{ + if (pTexture==NULL) return (RETURN_BAD_ARGUMENT); + if (SavePath[0]==0) {Message("uMod_TextureClient::SaveTexture( %#lX, %lu): %lu, SavePath not set\n", pTexture->Hash, pTexture->m_D3Dtex, this); return (RETURN_TEXTURE_NOT_SAVED);} + + wchar_t file[MAX_PATH]; + if (GameName[0]) swprintf_s( file, MAX_PATH, L"%ls\\%ls_C_%#lX.dds", SavePath, GameName, pTexture->Hash); + else swprintf_s( file, MAX_PATH, L"%ls\\C_%#lX.dds", SavePath, pTexture->Hash); + Message("uMod_TextureClient::SaveTexture( %ls): %lu\n", file, this); + + if (D3D_OK!=D3DXSaveTextureToFileW( file, D3DXIFF_DDS, pTexture->m_D3Dtex, NULL)) return (RETURN_TEXTURE_NOT_SAVED); + return (RETURN_OK); +} + + + + +int uMod_TextureClient::AddUpdate(TextureFileStruct* update, int number) //client must delete the update array +{ + Message("AddUpdate( %lu, %d): %lu\n", update, number, this); + if (int ret = LockMutex()) {gl_ErrorState |= uMod_ERROR_TEXTURE; return (ret);} + if (Update!=NULL) delete [] Update; + Update = update; + NumberOfUpdate = number; + return (UnlockMutex()); +} + + + +int uMod_TextureClient::MergeUpdate(void) +{ + if (NumberOfUpdate<0) {return (RETURN_OK);} + if (int ret = LockMutex()) {gl_ErrorState |= uMod_ERROR_TEXTURE ; return (ret);} + + Message("uMod_TextureClient::MergeUpdate(): %lu\n", this); + + for (int i=0; i0) to_lookup = new int[NumberOfUpdate]; + int num_to_lookup = 0; + + /* + * FileToMod contains the old files (textures) which should replace the target textures (if they are loaded by the game) + * Update contains the new files (textures) which should replace the target textures (if they are loaded by the game) + * + * Both arrays (FileToMod and Update) are sorted according to their hash values. + * + * First we go through both arrays linearly and + * 1) take over the old entry if the hash is the same, + * 2) release old fake texture (if target texture exist and is not in the Update) + * 3) or mark newly added fake texture (if they are not in FileToMod) + */ + + while (pos_old Update[pos_new].Hash) // this fake texture is new + { + to_lookup[num_to_lookup++] = pos_new++; // keep this fake texture in mind, we must search later for it through all original textures + // we increase only the new counter by one + } + else if (FileToMod[pos_old].Hash < Update[pos_new].Hash) // this fake texture is not in the update + { + for (int i=FileToMod[pos_old].NumberOfTextures-1; i>=0; i--) FileToMod[pos_old].Textures[i]->Release(); // we release the fake textures + if (FileToMod[pos_old].Textures!=NULL) delete [] FileToMod[pos_old].Textures; // we delete the memory + FileToMod[pos_old].NumberOfTextures = 0; + FileToMod[pos_old].Textures = NULL; + + pos_old++; // we increase only the old counter by one + } + else // the hash value is the same, thus this texture is in the array FileToMod as well as in the array Update + { + if (Update[pos_new].ForceReload) + { + if (FileToMod[pos_old].NumberOfTextures>0) + { + Update[pos_new].Textures = new IDirect3DBaseTexture9*[FileToMod[pos_old].NumberOfTextures]; + } + for (int i=0; iQueryInterface( IID_IDirect3D9, (void**)&base_texture); + switch (ret) + { + case 0x01000000L: + { + uMod_IDirect3DTexture9 *pTexture = (uMod_IDirect3DTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + case 0x01000001L: + { + uMod_IDirect3DVolumeTexture9 *pTexture = (uMod_IDirect3DVolumeTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DVolumeTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DVolumeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + case 0x01000002L: + { + uMod_IDirect3DCubeTexture9 *pTexture = (uMod_IDirect3DCubeTexture9*) FileToMod[pos_old].Textures[i];// + uMod_IDirect3DCubeTexture9 *pRefTexture = pTexture->CrossRef_D3Dtex; + pTexture->Release(); + i--; //after the Release of the old fake texture FileToMod[pos_old].Textures[i] is overwritten by entries with index greater than i + + uMod_IDirect3DCubeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (Update[pos_new]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pRefTexture)) + { + Message("MergeUpdate(): textures not switched %#lX\n", pRefTexture->Hash); + fake_Texture->Release(); + } + else + { + Update[pos_new].Textures[Update[pos_new].NumberOfTextures++] = fake_Texture; + fake_Texture->Reference = pos_new; + } + break; + } + default: + break; // this is no fake texture and QueryInterface failed, because IDirect3DBaseTexture9 object cannot be a IDirect3D9 object ;) + } + } + } + else // the texture might be loaded or not + { + Update[pos_new].NumberOfTextures = FileToMod[pos_old].NumberOfTextures; + Update[pos_new].Textures = FileToMod[pos_old].Textures; + FileToMod[pos_old].NumberOfTextures = 0; + FileToMod[pos_old].Textures = NULL; + } + // we increase both counters by one + pos_old++; + pos_new++; + } + } + + while (pos_old=0; i--) FileToMod[pos_old].Textures[i]->Release(); // we release the fake textures + //for (int i=0; iRelease(); // we release the fake textures + if (FileToMod[pos_old].Textures!=NULL) delete [] FileToMod[pos_old].Textures; // we delete the memory + FileToMod[pos_old].Textures = NULL; + pos_old++; + } + while (pos_new0) + { + uMod_IDirect3DTexture9* single_texture; + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) single_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleTexture(); //this texture must no be added twice + else single_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleTexture(); //this texture must no be added twice + + int num = OriginalTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalTextures[i]->CrossRef_D3Dtex==single_texture) + { + UnswitchTextures(OriginalTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalTextures[i], num_to_lookup, to_lookup); + } + + uMod_IDirect3DVolumeTexture9 *single_volume_texture; + if (ret == 0x01000000L) single_volume_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleVolumeTexture(); //this texture must no be added twice + else single_volume_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleVolumeTexture(); //this texture must no be added twice + num = OriginalVolumeTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalVolumeTextures[i]->CrossRef_D3Dtex==single_volume_texture) + { + UnswitchTextures(OriginalVolumeTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalVolumeTextures[i], num_to_lookup, to_lookup); + } + + uMod_IDirect3DCubeTexture9 *single_cube_texture; + if (ret == 0x01000000L) single_cube_texture = ((uMod_IDirect3DDevice9*)D3D9Device)->GetSingleCubeTexture(); //this texture must no be added twice + else single_cube_texture = ((uMod_IDirect3DDevice9Ex*) D3D9Device)->GetSingleCubeTexture(); //this texture must no be added twice + num = OriginalCubeTextures.GetNumber(); + for (int i=0; iCrossRef_D3Dtex==NULL || OriginalCubeTextures[i]->CrossRef_D3Dtex==single_cube_texture) + { + UnswitchTextures(OriginalCubeTextures[i]); //this we can do always, so we unswitch the single texture + LookUpToMod( OriginalCubeTextures[i], num_to_lookup, to_lookup); + } + } + + + + if (to_lookup != NULL) delete [] to_lookup; + + Message("uMod_TextureClient::MergeUpdate() END: %lu\n", this); + + CheckAgainNonAdded(); + return (UnlockMutex()); +} + + + +int uMod_TextureClient::LockMutex(void) +{ + if (( gl_ErrorState & (uMod_ERROR_FATAL | uMod_ERROR_MUTEX) )) return (RETURN_NO_MUTEX); + if (WAIT_OBJECT_0!=WaitForSingleObject( Mutex, 100)) return (RETURN_MUTEX_LOCK); //waiting 100ms, to wait infinite pass INFINITE + return (RETURN_OK); +} + +int uMod_TextureClient::UnlockMutex(void) +{ + if (ReleaseMutex(Mutex)==0) return (RETURN_MUTEX_UNLOCK); + return (RETURN_OK); +} + + + + + +int uMod_TextureClient::LookUpToMod( MyTypeHash hash, int num_index_list, int *index_list) +{ + if(NumberToMod>0) + { + if (index_list==NULL || num_index_list==0) + { + if (hashFileToMod[NumberToMod-1].Hash) return (-1); + int pos = NumberToMod/2; + int begin = 0; + int end = NumberToMod-1; + + // We look in the middle of the interval and each step we halve the interval, + // unless we find the texture or the size of the interval is less than 3. + // Note: contradicting to normal C-code here the interval includes the index "begin" and "end"! + while (begin+1 FileToMod[pos].Hash) // the new interval is the right half of the actual interval + { + begin = pos+1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else if (hash < FileToMod[pos].Hash) // the new interval is the left half of the actual interval + { + end = pos-1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else {return (pos); break;} // we hit the correct hash + } + for ( pos=begin; pos<=end; pos++) if (FileToMod[pos].Hash==hash) return (pos); + } + else + { + if (hashFileToMod[index_list[num_index_list-1]].Hash) return (-1); + int pos = num_index_list/2; + int begin = 0; + int end = num_index_list-1; + + // We look in the middle of the interval and each step we halve the interval, + // unless we find the texture or the size of the interval is less than 3. + // Note: contradicting to normal C-code here the interval includes the index "begin" and "end"! + while (begin+1 FileToMod[index_list[pos]].Hash) // the new interval is the right half of the actual interval + { + begin = pos+1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else if (hash < FileToMod[index_list[pos]].Hash) // the new interval is the left half of the actual interval + { + end = pos-1; // the new interval does not contain the index "pos" + pos = (begin + end)/2; // set "pos" somewhere inside the new interval + } + else {return (index_list[pos]); break;} // we hit the correct hash + } + for ( pos=begin; pos<=end; pos++) if (FileToMod[index_list[pos]].Hash==hash) return (index_list[pos]); + } + } + return (-1); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DVolumeTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( Volume %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DVolumeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + +int uMod_TextureClient::LookUpToMod( uMod_IDirect3DCubeTexture9* pTexture, int num_index_list, int *index_list) // should only be called for original textures +{ + Message("uMod_TextureClient::LookUpToMod( Cube %lu): hash: %#lX, %lu\n", pTexture, pTexture->Hash, this); + if (pTexture->CrossRef_D3Dtex!=NULL) return (RETURN_OK); // bug, this texture is already switched + int index = LookUpToMod( pTexture->Hash, num_index_list, index_list); + if (index>=0) + { + uMod_IDirect3DCubeTexture9 *fake_Texture; + if (int ret = LoadTexture( & (FileToMod[index]), &fake_Texture)) return (ret); + if (SwitchTextures( fake_Texture, pTexture)) + { + Message("uMod_TextureClient::LookUpToMod(): textures not switched %#lX\n", FileToMod[index].Hash); + fake_Texture->Release(); + } + else + { + IDirect3DBaseTexture9 **temp = new IDirect3DBaseTexture9*[FileToMod[index].NumberOfTextures+1]; + for (int j=0; jReference = index; + } + } + return (RETURN_OK); +} + + + + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DVolumeTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( Volume %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateVolumeTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DVolumeTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateVolumeTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DVolumeTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedVolumeTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( Volume %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + +int uMod_TextureClient::LoadTexture( TextureFileStruct* file_in_memory, uMod_IDirect3DCubeTexture9 **ppTexture) // to load fake texture from a file in memory +{ + Message("LoadTexture( Cube %lu, %lu, %#lX): %lu\n", file_in_memory, ppTexture, file_in_memory->Hash, this); + if (D3D_OK != D3DXCreateCubeTextureFromFileInMemoryEx( D3D9Device, file_in_memory->pData, file_in_memory->Size, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, (IDirect3DCubeTexture9 **) ppTexture)) + //if (D3D_OK != D3DXCreateCubeTextureFromFileInMemory( D3D9Device, file_in_memory->pData, file_in_memory->Size, (IDirect3DCubeTexture9 **) ppTexture)) + { + *ppTexture=NULL; + return (RETURN_TEXTURE_NOT_LOADED); + } + (*ppTexture)->FAKE = true; + + void *cpy; + long ret = D3D9Device->QueryInterface( IID_IDirect3DTexture9, &cpy); + if (ret == 0x01000000L) ((uMod_IDirect3DDevice9*)D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + else ((uMod_IDirect3DDevice9Ex*) D3D9Device)->SetLastCreatedCubeTexture(NULL); //this texture must no be added twice + + Message("LoadTexture( Cube %lu, %#lX): DONE\n", *ppTexture, file_in_memory->Hash); + return (RETURN_OK); +} + + + + diff --git a/uMod2/uMod_DXMain/uMod_TextureClient.h b/uMod2/uMod_DXMain/uMod_TextureClient.h new file mode 100644 index 0000000..a0a35f4 --- /dev/null +++ b/uMod2/uMod_DXMain/uMod_TextureClient.h @@ -0,0 +1,163 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_TEXTUREHANDLER_HPP +#define uMod_TEXTUREHANDLER_HPP + +#include +#include +#include "../uMod_GlobalDefines.h" +#include "..\uMod_Error.h" + + +class uMod_TextureServer; + +/* + * An object of this class is owned by each d3dXX device. + * functions called by the Server are called from the server thread instance. + * All other functions are called from the render thread instance of the game itself. + */ + +class uMod_TextureClient +{ +public: + uMod_TextureClient(uMod_TextureServer* server); + ~uMod_TextureClient(void); + + /** + * Enable/Disable the "save all texture" mode. (called from the server) + * @param val + * @return RETURN_OK on success + */ + int SaveAllTextures(bool val); + + /** + * Enable/Disable the "save all texture" mode. (called from the server) + * @param val + * @return RETURN_OK on success + */ + int SaveSingleTexture(bool val); + + /** + * Set the directory, wher the texture should be stored (called from the server) + * @param dir + * @return RETURN_OK on success + */ + int SetSaveDirectory( wchar_t *dir); + + /** + * Set the name of the game (default name of executabel without the extension .exe) (called from the server) + * @param name + * @return RETURN_OK on success + */ + int SetGameName( wchar_t *name); + + /** + * Set the key to got to the previous texture (called from the server) + * @param key + * @return RETURN_OK + */ + int SetKeyBack( int key) {if (key>0) KeyBack = key; return (RETURN_OK);} + /** + * Set the key for saving the texture (called from the server) + * @param key + * @return RETURN_OK + */ + int SetKeySave( int key) {if (key>0) KeySave = key; return (RETURN_OK);} + /** + * Set the key to go to the next texture (called from the server) + * @param key + * @return RETURN_OK + */ + int SetKeyNext( int key) {if (key>0) KeyNext = key; return (RETURN_OK);} + + /** + * Set the font color "during save single" texture mode. (called from the server) + * @param r red value (0..255) + * @param g green value (0..255) + * @param b blue value (0..255) + * @return + */ + int SetFontColour( DWORD r, DWORD g, DWORD b) {FontColour = D3DCOLOR_ARGB(255, r,g,b); return (RETURN_OK);} + /** + * Set the texture color "during save single" texture mode. (called from the server) + * @param r red value (0..255) + * @param g green value (0..255) + * @param b blue value (0..255) + * @return RETURN_OK + */ + int SetTextureColour( DWORD r, DWORD g, DWORD b) {TextureColour = D3DCOLOR_ARGB(255, r,g,b); return (RETURN_OK);} + + + /** + * The server add an update to the client.(called from server) + * @param update Pointer to an array of TextureFileStruct, the client \b must delete this array! + * @param number number of entries + * @return RETURN_OK on success + */ + int AddUpdate(TextureFileStruct* update, int number); + /** + * Merge the latest update (called from client -> e.g. uMod_IDirect3DDevice9::BeginScene()) + * @return RETURN_OK on success + */ + int MergeUpdate(void); + + + bool BoolSaveAllTextures; //< true if all textures should be saved + bool BoolSaveSingleTexture; //< true if "save single texture" mode is enabled + int KeyBack; //< key value for going to the previous texture + int KeySave; //< key value for saving the current texture + int KeyNext; //< key value for going to the next texture + + D3DCOLOR FontColour; //< color of the message ("save single texture" mode) + D3DCOLOR TextureColour; //< color of the texture ("save single texture" mode) + +private: + uMod_TextureServer* Server; //< Pointer to the server + wchar_t SavePath[MAX_PATH]; //< saving directory + wchar_t GameName[MAX_PATH]; //< game name + + TextureFileStruct* Update; //< array which stores the file in memory and the hash of each texture to be modded + int NumberOfUpdate; //< number of texture to be modded + + /** + * Lock the mutex. The mutex protect the AddUpdate and MergeUpdate function to be called simultaneously. + * @return RETURN_OK on success + */ + int LockMutex(); + /** + * Unloock the mutex. The mutex protect the AddUpdate and MergeUpdate function to be called simultaneously. + * @return RETURN_OK on success + */ + int UnlockMutex(); + HANDLE Mutex; //< The mutex protect the AddUpdate and MergeUpdate function to be called simultaneously. + + int NumberToMod; //< number of texture to be modded + TextureFileStruct* FileToMod; //< array which stores the file in memory and the hash of each texture to be modded + + + int LookUpToMod( MyTypeHash hash, int num_index_list, int *index_list); // called from LookUpToMod(...); + + +}; + + + +#endif /* uMod_TEXTUREHANDLER_HPP_ */ diff --git a/uMod2/uMod_DXMain/uMod_TextureServer.cpp b/uMod2/uMod_DXMain/uMod_TextureServer.cpp new file mode 100644 index 0000000..4d977e5 --- /dev/null +++ b/uMod2/uMod_DXMain/uMod_TextureServer.cpp @@ -0,0 +1,828 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + +uMod_TextureServer::uMod_TextureServer(wchar_t *game) +{ + Message("uMod_TextureServer(void): %lu\n", this); + + Mutex = CreateMutex(NULL, false, NULL); + + Clients = NULL; + NumberOfClients = 0; + LenghtOfClients = 0; + BoolSaveAllTextures = false; + BoolSaveSingleTexture = false; + SavePath[0] = 0; + + int len=0; + int path_pos=0; + int dot_pos=0; + for (len=0; lenpath_pos) len = dot_pos - path_pos; + else len -= path_pos; + + for (int i=0; ipData; //delete the file content of the texture + + num = OldMod.GetNumber(); + for (int i = 0; i < num; i++) delete[] OldMod[i]->pData; //delete the file content of the texture + + if (Pipe.In != INVALID_HANDLE_VALUE ) CloseHandle(Pipe.In); + Pipe.In = INVALID_HANDLE_VALUE; + if (Pipe.Out != INVALID_HANDLE_VALUE) CloseHandle(Pipe.Out); + Pipe.Out = INVALID_HANDLE_VALUE; +} + +int uMod_TextureServer::AddClient(uMod_TextureClient *client, TextureFileStruct** update, int* number) // called from a client +{ + Message("AddClient(%lu): %lu\n", client, this); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + + // the following functions must not change the original uMod_IDirect3DDevice9 object + // somehow on game start some uMod_IDirect3DDevice9 object are created, which must rest unchanged!! + // these objects are released and are not used for rendering + client->SetGameName(GameName); + client->SaveAllTextures(BoolSaveAllTextures); + client->SaveSingleTexture(BoolSaveSingleTexture); + client->SetSaveDirectory(SavePath); + if (KeyBack > 0) client->SetKeyBack(KeyBack); + if (KeySave > 0) client->SetKeySave(KeySave); + if (KeyNext > 0) client->SetKeyNext(KeyNext); + + if (FontColour>0u) + { + DWORD r = (FontColour>>16)&0xFF; + DWORD g = (FontColour>>8)&0xFF; + DWORD b = (FontColour)&0xFF; + client->SetFontColour( r, g, b); + } + if (TextureColour>0u) + { + DWORD r = (TextureColour>>16)&0xFF; + DWORD g = (TextureColour>>8)&0xFF; + DWORD b = (TextureColour)&0xFF; + client->SetTextureColour( r, g, b); + } + + + if (int ret = PrepareUpdate( update, number)) return (ret); // get a copy of all texture to be modded + + + if (NumberOfClients == LenghtOfClients) //allocate more memory + { + uMod_TextureClient** temp = NULL; + try {temp = new uMod_TextureClient*[LenghtOfClients + 10];} + catch (...) + { + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + if (int ret = UnlockMutex()) return (ret); + return (RETURN_NO_MEMORY); + } + for (int i=0; iHash == hash) //look through all current textures + { + if (force) {temp = CurrentMod[i]; break;} // we need to reload it + else + { + if (buffer!=NULL) delete [] buffer; + return (RETURN_OK); // we still have added this texture + } + } + if (temp==NULL) // if not found, look through all old textures + { + num = OldMod.GetNumber(); + for (int i=0; iHash == hash) + { + temp = OldMod[i]; + OldMod.Remove(temp); + CurrentMod.Add(temp); + if (force) break; // we must reload it + else + { + if (buffer!=NULL) delete [] buffer; + return (RETURN_OK); // we should not reload it + } + } + } + + bool new_file = true; + if (temp!=NULL) //if it was found, we delete the old file content + { + new_file = false; + if (temp->pData!=NULL) delete [] temp->pData; + temp->pData = NULL; + } + else //if it was not found, we need to create a new object + { + new_file = true; + temp = new TextureFileStruct; + temp->Reference = -1; + } + + temp->pData = buffer; + + /* + try + { + temp->pData = new char[size]; + } + catch (...) + { + if (!new_file) CurrentMod.Remove( temp); // if this is a not a new file it is in the list of the CurrentMod + delete temp; + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + return (RETURN_NO_MEMORY); + } + */ + + for (unsigned int i=0; ipData[i] = buffer[i]; + + temp->Size = size; + temp->NumberOfTextures = 0; + temp->Textures = NULL; + temp->Hash = hash; + + //if (new_file) temp->ForceReload = false; // no need to force a load of the texture + //else + temp->ForceReload = force; + + Message("End AddFile(%#lX)\n", hash); + if (new_file) return (CurrentMod.Add(temp)); // new files must be added to the list of the CurrentMod + else return (RETURN_OK); +} +/* +int uMod_TextureServer::AddFile(wchar_t* file_name, MyTypeHash hash, bool force) // called from Mainloop +// this functions does the same, but loads the file content from disk +{ + Message("uMod_TextureServer::AddFile( %ls, %#lX, %d): %lu\n", file_name, hash, force, this); + + TextureFileStruct* temp = NULL; + + int num = CurrentMod.GetNumber(); + for (int i = 0; i < num; i++) if (CurrentMod[i]->Hash == hash) + { + if (force) {temp = CurrentMod[i]; break;} + else return (RETURN_OK); + } + if (temp==NULL) + { + num = OldMod.GetNumber(); + for (int i = 0; i < num; i++) if (OldMod[i]->Hash == hash) + { + temp = OldMod[i]; + OldMod.Remove(temp); + CurrentMod.Add(temp); + if (force) break; + else return (RETURN_OK); + } + } + + FILE* file; + if (_wfopen_s(&file, file_name, L"rb") != 0) + { + Message("AddFile( ): file not found\n"); + return (RETURN_FILE_NOT_LOADED); + } + + fseek (file, 0, SEEK_END); + unsigned int size = ftell(file); + fseek (file, 0, SEEK_SET); + + bool new_file = true; + if (temp!=NULL) + { + new_file = false; + if (temp->pData!=NULL) delete [] temp->pData; + temp->pData = NULL; + } + else + { + new_file = true; + temp = new TextureFileStruct; + temp->Reference = -1; + } + + try + { + temp->pData = new char[size]; + } + catch (...) + { + if (!new_file) CurrentMod.Remove( temp); + delete temp; + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + return (RETURN_NO_MEMORY); + } + int result = fread(temp->pData, 1, size, file); + fclose(file); + if (result != size) + { + delete[] temp->pData; + if (!new_file) CurrentMod.Remove( temp); + delete temp; + return (RETURN_FILE_NOT_LOADED); + } + + temp->Size = size; + temp->NumberOfTextures = 0; + temp->Textures = NULL; + temp->Hash = hash; + + if (new_file) temp->ForceReload = false; + else temp->ForceReload = force; + + Message("End AddFile(%#lX)\n", hash); + if (new_file) return (CurrentMod.Add(temp)); + else return (RETURN_OK); +} +*/ + +int uMod_TextureServer::RemoveFile(MyTypeHash hash) // called from Mainloop() +{ + Message("RemoveFile( %lu): %lu\n", hash, this); + + int num = CurrentMod.GetNumber(); + for (int i = 0; i < num; i++) if (CurrentMod[i]->Hash == hash) + { + TextureFileStruct* temp = CurrentMod[i]; + CurrentMod.Remove(temp); + return (OldMod.Add(temp)); + } + return (RETURN_OK); +} + +int uMod_TextureServer::SaveAllTextures(bool val) // called from Mainloop() +{ + if (BoolSaveAllTextures == val) return (RETURN_OK); + BoolSaveAllTextures = val; + + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SaveAllTextures(BoolSaveAllTextures); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SaveSingleTexture(bool val) // called from Mainloop() +{ + if (BoolSaveSingleTexture == val) return (RETURN_OK); + BoolSaveSingleTexture = val; + + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SaveSingleTexture(BoolSaveSingleTexture); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetSaveDirectory(wchar_t *dir) // called from Mainloop() +{ + Message("uMod_TextureServer::SetSaveDirectory( %ls): %lu\n", dir, this); + int i = 0; + for (i = 0; i < MAX_PATH && (dir[i]); i++) SavePath[i] = dir[i]; + if (i == MAX_PATH) + { + SavePath[0] = 0; + return (RETURN_BAD_ARGUMENT); + } + else SavePath[i] = 0; + + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetSaveDirectory(SavePath); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetKeyBack(int key) // called from Mainloop() +{ + if (KeyBack == key || KeySave == key || KeyNext == key) return (RETURN_OK); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + KeyBack = key; + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetKeyBack(key); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetKeySave(int key) // called from Mainloop() +{ + if (KeyBack == key || KeySave == key || KeyNext == key) return (RETURN_OK); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + KeySave = key; + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetKeySave(key); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetKeyNext(int key) // called from Mainloop() +{ + if (KeyBack == key || KeySave == key || KeyNext == key) return (RETURN_OK); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + KeyNext = key; + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetKeyNext(key); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetFontColour(DWORD colour) // called from Mainloop() +{ + if (colour==0u) return (RETURN_OK); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + FontColour = colour; + DWORD r = (FontColour>>16)&0xFF; + DWORD g = (FontColour>>8)&0xFF; + DWORD b = (FontColour)&0xFF; + Message("uMod_TextureServer::SetFontColour( %u %u %u): %lu\n", r ,g ,b, this); + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetFontColour( r, g, b); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::SetTextureColour(DWORD colour) // called from Mainloop() +{ + if (colour==0u) return (RETURN_OK); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_SERVER; + return (ret); + } + TextureColour = colour; + DWORD r = (TextureColour>>16)&0xFF; + DWORD g = (TextureColour>>8)&0xFF; + DWORD b = (TextureColour)&0xFF; + Message("uMod_TextureServer::SetTextureColour( %u %u %u): %lu\n", r ,g ,b, this); + for (int i = 0; i < NumberOfClients; i++) + { + Clients[i]->SetTextureColour( r, g, b); + } + return (UnlockMutex()); +} + +int uMod_TextureServer::PropagateUpdate(uMod_TextureClient* client) // called from Mainloop(), send the update to all clients +{ + Message("PropagateUpdate(%lu): %lu\n", client, this); + if (int ret = LockMutex()) + { + gl_ErrorState |= uMod_ERROR_TEXTURE; + return (ret); + } + if (client != NULL) + { + TextureFileStruct* update; + int number; + if (int ret = PrepareUpdate( &update, &number)) return (ret); + client->AddUpdate(update, number); + } + else + { + for (int i=0; iAddUpdate(update, number); + } + } + return (UnlockMutex()); +} + +#define cpy_file_struct( a, b) \ +{ \ + a.ForceReload = b.ForceReload; \ + a.pData = b.pData; \ + a.Size = b.Size; \ + a.NumberOfTextures = b.NumberOfTextures; \ + a.Reference = b.Reference; \ + a.Textures = b.Textures; \ + a.Hash = b.Hash; } + +int TextureFileStruct_Compare( const void * elem1, const void * elem2 ) +{ + TextureFileStruct *tex1 = (TextureFileStruct*)elem1; + TextureFileStruct *tex2 = (TextureFileStruct*)elem2; + if (tex1->Hash < tex2->Hash) return (-1); + if (tex1->Hash > tex2->Hash) return (+1); + return (0); +} + +int uMod_TextureServer::PrepareUpdate(TextureFileStruct** update, int* number) // called from the PropagateUpdate() and AddClient. +// Prepare an update for one client. The allocated memory must deleted by the client. +{ + Message("PrepareUpdate(%lu, %d): %lu\n", update, number, this); + + TextureFileStruct* temp = NULL; + int num = CurrentMod.GetNumber(); + if (num>0) + { + try {temp = new TextureFileStruct[num];} + catch (...) + { + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + return (RETURN_NO_MEMORY); + } + + for (int i=0; iControl) + { + case CONTROL_END_TEXTURES: + { + Message("MainLoop: CONTROL_END_TEXTURES (): %lu\n", this); + update_textures=true; + break; + } + /* + case CONTROL_FORCE_RELOAD_TEXTURE: force=true; + case CONTROL_ADD_TEXTURE: + { + size = commands->Value; + Message("MainLoop: CONTROL_ADD_TEXTURE (%#lX %u, %u %u): %lu\n", commands->Hash, size, sizeof(MsgStruct), sizeof(char), this); + if (pos + sizeof(MsgStruct) + size <= num) AddFile( (wchar_t*) &buffer[pos + sizeof(MsgStruct)], commands->Hash, force); + //update_textures = true; + force = false; + break; + } + */ + case CONTROL_FORCE_RELOAD_TEXTURE_DATA: + { + texture_size = commands->Value; + texture_received = 0u; + texture_hash = commands->Hash; + texture_force=true; + try + { + texture_data = new char[texture_size]; + } + catch (...) + { + texture_size = 0u; + texture_data = (char*)0; + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + } + Message("MainLoop: CONTROL_FORCE_RELOAD_TEXTURE_DATA (%#lX %u, %u): %lu\n", texture_hash, texture_size, texture_data, this); + break; + } + case CONTROL_ADD_TEXTURE_DATA: + { + texture_size = commands->Value; + texture_received = 0u; + texture_hash = commands->Hash; + texture_force=true; + try + { + texture_data = new char[texture_size]; + } + catch (...) + { + texture_size = 0u; + texture_data = (char*)0; + gl_ErrorState |= uMod_ERROR_MEMORY | uMod_ERROR_SERVER; + } + Message("MainLoop: CONTROL_ADD_TEXTURE_DATA (%#lX %u, %u): %lu\n", texture_hash, texture_size, texture_data, this); + break; + } + case CONTROL_REMOVE_TEXTURE: + { + Message("MainLoop: CONTROL_REMOVE_TEXTURE (%#lX): %lu\n", commands->Hash, this); + RemoveFile(commands->Hash); + //update_textures = true; + break; + } + + case CONTROL_SAVE_SINGLE: + { + Message("MainLoop: CONTROL_SAVE_SINGLE (%d): %lu\n", commands->Value, this); + if (commands->Value == 0) SaveSingleTexture(false); + else SaveSingleTexture(true); + break; + } + case CONTROL_SAVE_ALL: + { + Message("MainLoop: CONTROL_SAVE_ALL (%d): %lu\n", commands->Value, this); + if (commands->Value == 0) SaveAllTextures(false); + else SaveAllTextures(true); + break; + } + case CONTROL_SET_DIR: + { + size = commands->Value; + if (pos + sizeof(MsgStruct) +size <= num) SetSaveDirectory( (wchar_t*) &buffer[pos + sizeof(MsgStruct)]); + break; + } + + case CONTROL_KEY_BACK: + { + Message("MainLoop: CONTROL_KEY_BACK (%#X): %lu\n", commands->Value, this); + SetKeyBack(commands->Value); + break; + } + case CONTROL_KEY_SAVE: + { + Message("MainLoop: CONTROL_KEY_SAVE (%#X): %lu\n", commands->Value, this); + SetKeySave(commands->Value); + break; + } + case CONTROL_KEY_NEXT: + { + Message("MainLoop: CONTROL_KEY_NEXT (%#X): %lu\n", commands->Value, this); + SetKeyNext(commands->Value); + break; + } + case CONTROL_FONT_COLOUR: + { + Message("MainLoop: CONTROL_FONT_COLOUR (%#X): %lu\n", commands->Value, this); + SetFontColour(commands->Value); + break; + } + case CONTROL_TEXTURE_COLOUR: + { + Message("MainLoop: CONTROL_TEXTURE_COLOUR (%#X): %lu\n", commands->Value, this); + SetTextureColour(commands->Value); + break; + } + default: + { + Message("MainLoop: DEFAULT: %lu %lu %#lX\n", commands->Control, commands->Value, commands->Hash, this); + break; + } + } + pos += sizeof(MsgStruct) + size; + } + } + if (update_textures) {PropagateUpdate(); update_textures=false;} + } + else + { + Message("MainLoop: error in ReadFile()\n"); + delete [] buffer; + ClosePipe(); + return (RETURN_OK); + } + } + + delete [] buffer; + return (RETURN_OK); +} + +int uMod_TextureServer::OpenPipe(wchar_t *game) // called from InitInstance() +{ + Message("OpenPipe: Out\n") + // open first outgoing pipe !! + Pipe.Out = CreateFileW(PIPE_Game2uMod, // pipe name + GENERIC_WRITE, // write access + 0, // no sharing + NULL, // default security attributes + OPEN_EXISTING, // opens existing pipe + 0, // default attributes + NULL); // no template file + + // Exit if an error other than ERROR_PIPE_BUSY occurs. + if (Pipe.Out == INVALID_HANDLE_VALUE) return (RETURN_PIPE_NOT_OPENED); + + unsigned int len = 0u; + while (game[len]) len++; + len++; //to send also the zero + unsigned long num; + //send name of this game to uMod_GUI + WriteFile(Pipe.Out, (const void*) game, len * sizeof(wchar_t), &num, NULL); + + // now we can open the pipe for reading + Message("OpenPipe: In\n"); + Pipe.In = CreateFileW(PIPE_uMod2Game, // pipe name + GENERIC_READ, // read access + 0, // no sharing + NULL, // default security attributes + OPEN_EXISTING, // opens existing pipe + 0, // default attributes + NULL); // no template file + + if (Pipe.In == INVALID_HANDLE_VALUE) + { + CloseHandle(Pipe.In); + Pipe.In = INVALID_HANDLE_VALUE; + return (RETURN_PIPE_NOT_OPENED); + } + + Message("OpenPipe: Done\n"); + return (RETURN_OK); +} + +int uMod_TextureServer::ClosePipe(void) //called from ExitInstance, this must be done, otherwise the Mainloop will wait endless on the ReadFile() +{ + Message("ClosePipe:\n"); + + // We close the outgoing pipe first. + // The GUI will notice that the opposite side of it incoming pipe is closed + // and closes it outgoing (our incoming) pipe and thus cancel the ReadFile() in the Mainloop() + + if (Pipe.Out != INVALID_HANDLE_VALUE) + { + DisconnectNamedPipe(Pipe.Out); + CloseHandle(Pipe.Out); + Pipe.Out = INVALID_HANDLE_VALUE; + } + + if (Pipe.In != INVALID_HANDLE_VALUE) + { + DisconnectNamedPipe(Pipe.In); + CloseHandle(Pipe.In); + Pipe.In = INVALID_HANDLE_VALUE; + } + + return (RETURN_OK); +} diff --git a/uMod2/uMod_DXMain/uMod_TextureServer.h b/uMod2/uMod_DXMain/uMod_TextureServer.h new file mode 100644 index 0000000..8a31580 --- /dev/null +++ b/uMod2/uMod_DXMain/uMod_TextureServer.h @@ -0,0 +1,110 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +#ifndef uMod_TEXTURESERVER_H_ +#define uMod_TEXTURESERVER_H_ + +#include "../uMod_GlobalDefines.h" +#include "uMod_ArrayHandler.h" + + +/* + * An object of this class is created only once. + * The Mainloop functions is executed by a server thread, + * which listen on a pipe. + * + * Functions called by the Client are called from the a thread instance of the game itself. + * Nearly all other functions are called from the server thread instance. + */ + + +class uMod_TextureClient; + +class uMod_TextureServer +{ +public: + uMod_TextureServer(wchar_t *name); + ~uMod_TextureServer(void); + + int AddClient(uMod_TextureClient *client, TextureFileStruct** update, int* number); // called from a Client + int RemoveClient(uMod_TextureClient *client); // called from a Client + + int OpenPipe(wchar_t *name); // called on initialization of our d3d9 fake dll + int ClosePipe(void); // called on exit of our d3d9 fake dll + int MainLoop(void); // is executed in a server thread + + + // following functions are only public for testing purpose !! + // they should be private and only be called from the Mainloop + + int AddFile( char* buffer, unsigned int size, MyTypeHash hash, bool force); // called from Mainloop(), if the content of the texture is sent + int AddFile( wchar_t* file_name, MyTypeHash hash, bool force); // called from Mainloop(), if the name and the path to the file is sent + int RemoveFile( MyTypeHash hash); // called from Mainloop() + + int SaveAllTextures(bool val); // called from Mainloop() + int SaveSingleTexture(bool val); // called from Mainloop() + + int SetSaveDirectory( wchar_t *dir); // called from Mainloop() + + + int SetKeyBack( int key); // called from Mainloop() + int SetKeySave( int key); // called from Mainloop() + int SetKeyNext( int key); // called from Mainloop() + + int SetFontColour(DWORD colour); // called from Mainloop() + int SetTextureColour(DWORD colour); // called from Mainloop() + +private: + bool BoolSaveAllTextures; + bool BoolSaveSingleTexture; + wchar_t SavePath[MAX_PATH]; + wchar_t GameName[MAX_PATH]; + + int PropagateUpdate(uMod_TextureClient* client=NULL); // called from Mainloop() if texture are loaded or removed + int PrepareUpdate(TextureFileStruct** update, int* number); // called from PropagateUpdate() and AddClient() + // generate a copy of the current texture to be modded + // the file content of the textures are not copied, the clients get the pointer to the file content + // but the arrays allocate by this function, must be deleted by the client + + int LockMutex(); + int UnlockMutex(); + HANDLE Mutex; + + + int KeyBack; + int KeySave; + int KeyNext; + + DWORD FontColour; + DWORD TextureColour; + + + PipeStruct Pipe; + + uMod_TextureClient** Clients; + int NumberOfClients; + int LenghtOfClients; + + uMod_FileHandler CurrentMod; // hold the file content of texture + uMod_FileHandler OldMod; // hold the file content of texture which were added previously but are not needed any more + // this is needed, because a texture clients might not have merged the last update and thus hold pointers to the file content of old textures +}; + + +#endif /* uMod_TEXTURESERVER_H_ */ diff --git a/uMod2/uMod_Error.h b/uMod2/uMod_Error.h new file mode 100644 index 0000000..d7a790e --- /dev/null +++ b/uMod2/uMod_Error.h @@ -0,0 +1,73 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +#ifndef uMod_ERROR_H_ +#define uMod_ERROR_H_ + + +// define return values, a value less than zero indicates an error +#define RETURN_OK 0 + +#define RETURN_FATAL_ERROR -1 +#define RETURN_NO_MEMORY -2 +#define RETURN_BAD_ARGUMENT -3 + +#define RETURN_NO_IDirect3DDevice9 -10 + +#define RETURN_TEXTURE_NOT_LOADED -20 +#define RETURN_TEXTURE_NOT_SAVED -21 +#define RETURN_TEXTURE_NOT_FOUND -22 +#define RETURN_TEXTURE_ALLREADY_ADDED -23 +#define RETURN_TEXTURE_NOT_SWITCHED -24 + +#define RETURN_LockRect_FAILED -30 +#define RETURN_UnlockRect_FAILED -31 +#define RETURN_GetLevelDesc_FAILED -32 + + +#define RETURN_NO_MUTEX -40 +#define RETURN_MUTEX_LOCK -41 +#define RETURN_MUTEX_UNLOCK -42 + +#define RETURN_UPDATE_ALLREADY_ADDED -50 +#define RETURN_FILE_NOT_LOADED -51 + +#define RETURN_PIPE_NOT_OPENED 60 + + + + + +// define error states +#define uMod_ERROR_FATAL 1u +#define uMod_ERROR_MUTEX 1u<<1 +#define uMod_ERROR_PIPE 1u<<2 +#define uMod_ERROR_MEMORY 1u<<3 +#define uMod_ERROR_TEXTURE 1u<<4 +#define uMod_ERROR_MULTIPLE_IDirect3D9 1u<<5 +#define uMod_ERROR_MULTIPLE_IDirect3DDevice9 1u<<6 +#define uMod_ERROR_UPDATE 1u<<7 +#define uMod_ERROR_SERVER 1u<<8 + + + + + + +#endif /* uMod_ERROR_H_ */ diff --git a/uMod2/uMod_GUI/bin/README_Deutsch.txt b/uMod2/uMod_GUI/bin/README_Deutsch.txt new file mode 100644 index 0000000..7bc70c8 --- /dev/null +++ b/uMod2/uMod_GUI/bin/README_Deutsch.txt @@ -0,0 +1,116 @@ +Warnung: Du verwendest diese Programm auf eigene Gefahr hin! +1) Wenn das Programm abstürzt, wirst du wahrscheinlich keinen Support + vom Spielehersteller bekommen. Aber du kannst den Fehler gerne + angeben unter: http://code.google.com/p/texmod/issues/list +2) Spiele können detektieren, ob sie verändert werden, daher riskierst du + einen Bann deines online Accounts. +3) Dies ist eine open-source Projekt. Der Code kann von jedem erhalten, verändert + und kompiliert werden. Lade Universal Modding Engine nur von offiziellen Quellen runter, + denen du vertraust. Lade es selbst runter und verwende keine Versionen, + die du von Team- oder Gildenmitgliedern geschickt bekommen hast. + http://code.google.com/p/texmod/downloads/list + + +Universal Modding Engine verwendet die D3DX9_43.dll (32bit). Wegen den EULA kann +diese dll nicht mit Universal Modding Engine mit geliefert werden. Wenn diese dll auf +deinem System nicht installiert ist, wird dich Universal Modding Engine darauf hinweisen. + + +Was kann Universal Modding Engine (uMod) V1.0? + +-einzelne Texturen aus einem Spiel extrahieren und speichern (Die Zieltextur kann im Spiel geändert werden.) +-alle Texturen aus einem Spiel extrahieren und speichern +-Texturen in ein Spiel laden und Zieltexturen ersetzen +-Support einzelner dds Texturen +-Support von zip-Dateien +-Support der originalen TexMod *.tpf Datein + +Alle diese Optionen können während des Spieles an und aus geschaltet werden! +Du kannst also nach einer Textur suchen, diese speichern, sie anschließend +editieren, sie in das Spiel laden, sie nach bearbeiten und wieder in das +Spiel laden, ... oder Mods aktivieren und deaktivieren +und das alles ohne das Spiel neu starten zu müssen. + +Randbemerkung: Wenn alle Texturen gespeichert werden sollen, so geschieht das nur, +wenn die Texturen vom Spiel geladen werden und auch nur in dem Moment, wenn sie +geladen werden. Stellst du diese Option an, während die Map bereits geladen ist, wird +wahrscheinlich nichts geschehen, da alle Texturen für diese Map bereits geladen sind. +Wechsle also die Map oder lade erneut. + +Zip Dateien können eine "texmod.def" Datei enthalten, welche die Hash-Werte und +Dateinamen enthält. Jede Zeile sollte dem Format "hash|filename.dds" entsprechen. +Wenn es keine "texmod.def" Datei enthält, wird jede Datei entpackt und jene, deren +Namen auf das Wildcard "*_hash.dds" zutrifft, werden benutzt. +Die Zip Datei kann eine "Comment.txt" Datei enthalten. Der Inhalte wird als Kommentar +in der GUI angezeigt. + +Wenn du einzelne Dateien lädst, sollten diese dem Wildcard "*_hash.dds" entsprechen. + + +Wie interagiert Universal Modding Engine mit den Spielen? + +Universal Modding Engine klingt sich zwischen die Verbindung vom Spiel und DirectX ein. +Das verlangt, dass Universal Modding Engine bereits vor dem Spiel gestartet wird. + +Die GUI von Universal Modding Engine fungiert als Server. Ein Spiel, in das sich erfolgreich +eingeklingt wurde, verbindet sich beim Programmstart mit dem Server. +Die GUI von Universal Modding Engine kann mehrere Spiele gleichzeitig verwalten. +Jede Instanz eines Spieles wird auch separat gehandhabt (wenn ein Spiel +mehrfach gestartet wird). + + +Wie bekomme ich Universal Modding Engine zum laufen? + +Es gibt drei Wege wie uMod sich in die DirectX Verbindung einklinken kann: +(Benutze NICHT mehrere Methoden gleichzeitig!) + +1) Füge die Spiel-exe über das Menü "Einstellungen->Spiel hinzufügen" hinzu. + Für Steam siehe unten. + + bekannte Probleme: Guild Wars (Win XP) + +2) Starte das Spiel direkt durch OTM über das Menü + "Einstellungen->Sarte Spiel durch OTM" oder + "Einstellungen->Sarte Spiel durch OTM (mit Kommandozeile)". + Das Spiel startet sofort. + +3) Kopiere die d3d9.dll (vom uMod Verzeichnis) in das Spiele Verzeichnis. + Einige Spiele laden eine dll zuerst aus dem eigenen Verzeichnis bevor sie im + Systemverzeichnis suchen. Nur für diese Spiele wird diese Methode funktionieren. + WARNUNG: Kopiere diese dll niemals in das Systemverzeichnis!! + + bekannte Probleme: Guild Wars + +Wenn du dich für die erste oder dritte Methode entschieden hast, starte einfach +Universal Modding Engine und danach das Spiel. Starte das Spiel in beiden Fällen NICHT über +Universal Modding Engine . + +Wenn das Spiel startet und alles glatt läuft, öffnet sich sofort ein neuer Tab in uMod. +In diesem Tab kannst du nun das Spiel modden. Drücke den "Update" Button um +die Einstellungen an das Spiel zu senden. Du kannst deine aktuellen Einstellungen auch +als ein Template speichern. Ein Template kann auch als Standard eingestellt werden. +Es wird dann automatisch geladen und an das Spiel gesendet, wenn +dieses Spiel das nächste Mal gestartet wird. + +Um einen Mod zu laden, musst du das Häkchen vor den Namen setzen. Wenn du +den Mod entladen willst, entferne das Häkchen und klicke auf "Update". + +Der Update Button lädt nur Veränderungen (wenn 1) Pakete aus der Liste entfernt +wurden, 2) du die Häkchen verändert hast oder 3) sich die Reihenfolge geändert hat) +Der "neu laden" Button erzwingt das Neuladen von Festplatte (z.B. wenn du die +Texturen verändert hast). + +Weil verschiedene Mods die gleiche Ziel-Textur verändern könnten, wird nur die +Mod-Textur des ersten Mods berücksichtigt. Die Aktion dieses Mods (also Laden oder +Entladen) wird durchgeführt, ungeachtet dessen, was die restlichen Mods mit der +Ziel-Textur machen sollen. + + +Wie bekommt man Universal Modding Engine mit Steam zum Laufen? + +uMod schaut auf den Namen und auf das Verzeichnis der ausgeführten Spiel-exe. +Daher solltest du nicht die steam.exe sondern die Spiel.exe hinzufügen. +z.B.: C:\Steam\SteamApps\acoount_name\portal\hl2.exe +Wenn du die entsprechende exe nicht findest, kannst du das Spiel normal starten und +über den TaskManager die entsprechende exe suchen. Über Rechstklick->Eigenschaften +erfährst du dann auch den Pfad der exe. \ No newline at end of file diff --git a/uMod2/uMod_GUI/bin/README_English.txt b/uMod2/uMod_GUI/bin/README_English.txt new file mode 100644 index 0000000..44b7f0d --- /dev/null +++ b/uMod2/uMod_GUI/bin/README_English.txt @@ -0,0 +1,107 @@ +WARNING: You use this program at your own risk! +1) If the program crash, you won't get probably any support from the game developer, + but you can report the bug under http://code.google.com/p/texmod/issues/list +2) Games can detected if they are modified, so you might risk a ban + of your online account! +3) This is an open-source project. The code can be retrieved, modified and compiled + by everyone. Download Universal Modding Engine only from sources you trust! + Download it by your self and don't use versions, send to you by team or guild members! + http://code.google.com/p/texmod/downloads/list + +Universal Modding Engine uses the D3DX9_43.dll (32bit). Due to the EULA this dll +cannot be delivered together with Universal Modding Engine . If D3DX9_43.dll is not +installed on your system, Universal Modding Engine will give you a hint at program start. + + +What can Universal Modding Engine (uMod) V1.0? + +-extract and save single textures from a DX9 game (the target texture can be toggled in the game) +-extract and save all textures from a DX9 game +-load textures into a game to replace target textures +-support single dds texture +-support zip-files as whole mod package +-support the original TexMod *.tpf files + +All these options can be switched on or off, while the game is already running! +So you can search for a texture in the game, save it to disk, edit it, +load it into the game, edit it again and load it into the game again, ..., +actiavate or deactivate mods and all without a restart of the game. + +side note: If "save all textures" is switched on, the texture will only be saved, if +the textures are loaded by the game and only in the moment they are loaded. +If you switch this option on, while a map is loaded, probably nothing will hapen, +because all textures are loaded for this map. Change the Map or reload it again. + +Zip files can include a "texmod.def" file which contains the hash and the file name. +Each line should be in the format "hash|filename.dds" +If it does not contain a "texmod.def" each file will be unpacked and those which match +the wildcard "*_hash.dds" will be used. +The zip file can include a "Comment.txt" file. The content will be shown as comment +in the GUI. + +If you load single files, they should match the wildcard "*_hash.dds" + + +How does Universal Modding Engine interact with the game? + +Universal Modding Engine intercept the connection between the game and DirectX. +It is required, that Universal Modding Engine is running before the game is started. + +The GUI of Universal Modding Engine act as a server. A game which is successfully +intercepted with the Universal Modding Engine-dll will connect on program start to the server. +The GUI of Universal Modding Engine can handle multiple games at the same time. It will +also process each instance of a game as separate process (if the same game +was started more than once). + + +How to get Universal Modding Engine work? + +There are three ways how Universal Modding Engine can intercept the DirectX connection: +(Do NOT use more than one method simultaneously!) + +1) Add the games-binary through the menu "Main->Add game" + For Steam see below. + + known problems: Guild Wars (Win XP) + +2) Start the game directly through uMod though the menu + "Main->Start game through uMod" or + "Main->Start game through uMod (with command line)". + The game start immediately. + +3) Copy the d3d9.dll (from the Universal Modding Engine directory) into the game directory. + Some games load a dll first from their own directory before they look up the system directory. + Only for these games this method will work. + WARNING: never copy this dll into your system directory!! + + known problems: Guild Wars + +If you have chosen the first or third method, you simply start Universal Modding Engine +and afterwards the game. Do NOT start the game through Universal Modding Engine. + +If the game starts and all works fine, a new tab opens immediately in uMod. +In this tab you can now mod the game. Press the "update" button to commit +the changes to the game. You can also save your current settings as a template. +One template can be set as default for a game, which will be loaded and +and committed automatically when you start this game the next time. + +To load a mod, you must set the check mark of the file. If you wish to unload a mod, +just remove the check mark and click on update again. + +Clicking on update will only update the differences (if packages have been +removed from the list, you toggled check marks or changed the order). The reload +button forces to reload from disk (if you have edited the texture itself). + +Due to the fact that different mods can modify the same target texture, only the +mod-texture of the first file in the list is taken into account. The action of this file +(load or unload) is proceeded regardless of what the following mods are opposed +to do with their mod-textures. + + +How to get Universal Modding Engine work together with Steam? + +Universal Modding Engine looks for the name and the path of the executed binary. +Thus you shall not add the steam.exe but rather the game.exe +e.g.: C:\Steam\SteamApps\acoount_name\portal\hl2.exe +If you cannot find the exe, just start the game and use the TaskManager +to search for it. You can figure out the path through right click->properties. \ No newline at end of file diff --git a/uMod2/uMod_GUI/bin/languages/Example_uMod_LanguagePack_English.txt b/uMod2/uMod_GUI/bin/languages/Example_uMod_LanguagePack_English.txt new file mode 100644 index 0000000..9aba258 --- /dev/null +++ b/uMod2/uMod_GUI/bin/languages/Example_uMod_LanguagePack_English.txt @@ -0,0 +1,152 @@ +If you have created a language package and would like to add to the officially download, please send it to me. +Email address and support can be found at http://code.google.com/p/texmod/ + + +The file name must match the wildcard uMod_LanguagePack_NAMEOFLANGUAGE.txt +Format of an entry is divided into 3 parts: 1) Keyword directly followed by a colon, 2) message, and 3) end symbol "|" +Restriction of the the message: do not use "|" within a message!! + +You can also use utf-16LE encoding, but you have to label the file as uMod_LanguagePackU_NAMEOFLANGUAGE.txt + +comments must start with an "#" and must end with | + +e.g. + +# + +this is a comment + +| + +Keyword: + +Message1 line1 +Message1 line2 + +| + +Keyword2:Message2| +Keyword3:Message3 line1 +Message3 line2| + + +There is no need to include all keywords, since English is loaded each time as default and afterwards the entries are replaced. +English itself is compiled into the uMod_GUI.exe, thus there exists no uMod_LanguagePack_English.txt. + +The following list is an example of how an English package would look like (maybe not all keywords are present). + + + +MenuHelp: +Help| +MenuAbout: +About| +MenuAcknowledgement:Acknowledgement| +MenuStartGame:Start game through uMod| +MenuStartGameCMD :Start game through uMod (with command line)| +MenuUseHook:Use global hook| +MenuAddGame: +Add game| +MenuDeleteGame: +Delete Game| +MenuLoadTemplate:Load template| +MenuSaveTemplate:Save template| +MenuSaveTemplateAs:Save template as ...| +MenuSetDefaultTemplate:Set template as default| +MenuLanguage:Change language| +MenuExit:Exit| +MainMenuMain:Main| +MainMenuHelp: +Help| + + +ButtonOpen: +Open texture| +ButtonDirectory: +save directory| +ButtonUpdate: +Update| +ButtonReload:Update (reload)| + + +ChooseFile:Choose a file| +ChooseDir: +Choose a directory| +CheckBoxSaveSingleTexture: +Save single texture| +TextCtrlTemplate:Template: | +CheckBoxSaveAllTextures: +Save all textures| +TextCtrlSavePath: +Save path: | +SelectLanguage: +Select a language| +StartGame:Select the game to start.| +CommandLine:Set command line arguments.| +ChooseGame: +Select a game binary. +DeleteGame: +Select the games to be deleted.| +GameAlreadyAdded: +Game has been already added.| +ExitGameAnyway: +Closing Universal Modding Engine while a game is running might lead to a crash of the game. +Exit anyway?| +NoComment: +No comment.| +Author: +Author: | + + +Error_GameIsHooked:The global hook is active and this game will be injected! Please delete the game from the list or disable the hook.| +Error_ProcessNotStarted:The game could not be started.| +Error_RemoveHook:Removing the Hook while a game is running might lead to crash.| +Error_FileNotSupported: +This file type is not supported:| +Error_DLLNotFound: +Could not load the dll. +The dll injection won't work. +This might happen if D3DX9_43.dll is not installed on your system. +Please install the newest DirectX End-User Runtime Web Installer.| +Error_FktNotFound: +Could not load function out of dll. +The dll injection won't work.| +Error_AlreadyRunning:An other instance of Universal Modding Engine is already running.| +Error_Send: +Could not send to game.| +Error_KeyTwice: +You assigned a key twice.| +Error_NoSavePath: +You did not set a save path.| +Error_KeyNotSet: +At least one key is not set.| +Error_SaveFile: +Could not save to file.| +Error_NoPipe: +Pipe is not opened.| +Error_WritePipe: +Could not write in pipe.| +Error_FlushPipe: +Could not flush pipe buffer.| +Error_Hash: +Could not find hash, maybe file is not named as *_HASH.dds| +Error_FileOpen: +Could not open file.| +Error_FileRead: +Could not read file.| +Error_Memory: +Could not allocate enough memory| +Error_Unzip: +Could not unzip.| +Error_ZipEntry: +Could not find zip entry.| +KeyBack: +Back| +KeySave: +Save| +KeyNext: +Next| +FontColour: +Font colour (RGB):| +TextureColour: +Texture colour (RGB):| \ No newline at end of file diff --git a/uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Deutsch.txt b/uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Deutsch.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8e2700cfe45d81d128a9f64dc21a11375a116aa GIT binary patch literal 6508 zcmchc+fEx-6o&UTPcc<*nku1E)0@ss1sIYjkVH6XqTWOfw!!rY83O_JQ7iQ(&(N!= z?f>oN<-KRdHl(U53m<0oUWb4E>#&Ev|N1%<;X}C5`_G{lX5lmp!YKR}w)8sEl}We^ zPxUzp=b_X$?)LSY6@Gt55~f-=*NWfu9XW-5AL(khw(=wlC370CC8wvmr+OdjZxVO6 zLPy_*;XuC;DVx8QQXJpl>7T>}t;}oP@JXe<5kU3q70V?aAua zzmQslZ)DFvnu_pT{*Cp*m#)6w$~tiCg$EVwZ)90dm`?Q?O6L=;nF_y7Tw5&f6yZwi zX2J~nyYW5uVn^4yYY;h;=7}u0RMb94w5tfTBn`{v`df{u#fF&AB*_s>(La>U9qE6q zdt=37q+duY8&`^WuW5fNfUlq0cD(vFZ`WlvKYyoHO#;qAbyssXG( ztuL!D<bYS70kg+{I z{U#du{wf3a!^gY34w8c(DC9C0kO=pt>ju&TNOel;@&tgv^L zwjD_tRU+GygfiH5{JyUSU$-ZeW|Hatz>~SOH=}NORmY~3PAqOmFO4_N99tbDI!($v zs|!f-?vmoAyzxGmdfG% zwYSh<@p5LawmLBrudTm6lFpC%13xNYvu{-WHXGA^EOyWLXh}s`4R`OdP(m@`mUvyIbh9U{BP zGQPtDG%$q}svX=j#&L~V#HJr2Mg1)#i%-vYa3GtIH`3K!_(Ok_@K9H;V}-yADmyIk z2;d>p6T1q1QWsf;BqVp`8L>egmJemiB;I%2nbq)yDtoIHpvJUT)d5at5l2|Lr7WFE z8|-5}9)q*l$NNu_6EC#J*~?Yt!RK0qWr?eHhwf*5-;ph3@Kjf*4E(b1mZ?Nx7WL1< z`{j)COkVipt)HSij&zo}th$m_bbBzijG|IE*+qw8O-EiEi@d*1!dJS!D_Qh2 zqGR4AUL(1g|4a_(arDV@qJjiwW{U}*$yU6B6K-p$sRBEy$I)l^0mF^E4qEpW-P;2saE1tERQ9P(2ZQRT&?&dhBF8W``xmh);vyQPBZZIwQ zOb(CfIk3=rKw>qg`xN~*kyl?biKGfypPnpFs*z~R0_>o(=lPT83zmXgv+uz;^I}zp zU{<)%tU>nBtLP3)Nt|b?68U-Q_2L@HkmpP*JaMs8w)vl)m-xh&S4-H`JVn$sat0+9 zHX-qy*^4Ncj{5nch!cW!CaPky51NrHs2RP1};(D@(bQsXS2L3maD60fu=_KWPhpS!3q{UjS=PCTFoOg!8X5N z)dcTgBo&W$W|}McX-{LEot7y~Z5N6KSo*2O{dghm)*W*OahHzGL}1y3q;EBKKh<2` z*88?N+LctQSRQ$2RC=0I_sXWcoKLyt{0UEUu5sy1koE-T%cOHowaU|!eH4AhUru~g zxw(b*l*^x>`l-wjCoWWIW(S_-=AFHc6&3ncD|nt>)#o#a-F=kJhjkVZ+jHsT`3^j2 z=Fl%u!@lnEyrk)y^K4)1Yz@yB$yKY}=Fwf2^y7MyWj0uK+g;dJ>c0wLYZY@4Yh(49 z59rt)uTIq`f$Qpy?Rg>Zd1hE@Huw}-ZuPUN15V>7=Tli_*hC$-?Ko+-O%IvGk7XIN;3oj* zd#7)|>gpr|ze>4U!a(~&-WpQY3Ed-^hckv|V~XPBnx zzJ3SkBCV$lJ@4zvYvTEabv zN7{cVP31{b&Vg3C}^1r6d;0Kb&*~WpcmhA_Jb47Ek4|ZQ^f@w$$f4dRI{3BCAJ=WOXyzFTVQAgxI2d)afCW7^Zqf*r_R$!sdq!dqEO?LD8N z*3}8SFvG?o4a~;Uu-G-tny?pU!hdSO2TfV@Y^Ec!uP%!Uj%BYCQZI$srG9(!o_?tw zWXT}2Eq|%eMaxjq-)TKHj};rrhR0g>P~W?%tq&#bD}8pPb(G^m7DmlA$2~t$jbfHs z)fy_;NPaSrH1QslS)37nV zBWVYc250JWVH{mBv=Fy#Ep)UVRfDR(sm|I^tp(=tKTAS?rAq=gC`!Q z3z%%~f9@QsSB-*YOcH^js~CJIH%on*sG?vc)rs%L*`ku&R9~~Wpga=Oz?&>2C(B$z zo-IdqE8SH`d7i$XMRg}LpBmt5w%4k=?0S*DlY}*`Cr_wgchk4(1Mr<1)@Eft+sIj# z9u_@=dQL3Kyk~sBd-VZfTy_>%enYoc1Z62`_wigzM3=4{dR`bYrn64&V`a z?Mf29kZn!IcqcKjT-KId+#LzS$XRQkS5isp-Nji;&16TtZ&cz^@ag|BV=+4Pw9m~7 zJTI)U{kLRwIlo*d>Q#Cs-(O1Bt}tBW-mQ7hYj(38&F_=X!VBVYob#u|55Kyjel=gZ z8By5KUdK-ELmbtJWYg-lxh!<-%U{36>f#NE4(6Bv+^>Ky-1P=A|%Euf0r#q-~`^u%f6iQ@iI&-vevF1<*iQaCzr-)9fo(B@@ZHvF2k zFvGzyPUu(Z`!5umwv^80YI-lTH2$B#bur!odPUT=uJ>c+TGVF0pW{su6_vce53gZP z=W0{Gjt=K)uBN&!*<*Hieq*J(9@wsAbX}jwHCB#wkKJXe80rpBcu)FNZy#5s#TNL@ UMZ6Qfz8zG<^4{@!I(>He7ryoUasU7T literal 0 HcmV?d00001 diff --git a/uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Russian.txt b/uMod2/uMod_GUI/bin/languages/uMod_LanguagePackU_Russian.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a3fc9841a9013ff4a42a8a0774079fb0f9f2858 GIT binary patch literal 6628 zcmchb>u*y>5XJYy{Zy$^A5>IT3kIYrR1i6i9g-X3#BrX21VoBJ6%q>A1wG^?T$rcU6^rm_O$&&*;k-I!x zRE+1x@HHh{Tl&5woPmUutg9zOUy3NOcc|B~ByL1hgI4UGiTl}sJ!_J(AR8^NFRwXORBk_(t5{BE>zpT@jBUxe!Pi35aD*Vt?C%fT}M@S7=6#fg_wgCt;3_bb`Ymh zw#Ri(cJ0fuLDXzN5C8r5*C(BSquAGuF=V_u#sFBgj_)U#`fD$$sf;a%mplijI!qE0>JusuZ& zq=T4hpRY2fclzlu4xGeM)!klgwa`=*V;S{pJVwWJsa@srm0rvpJ=sN90gqQ=Ex<1@ zgHIpK1ha~Pb(vLV^5b0OvjZHSBCo9Ws`Yeo zi($>J0bA5H9r9F@8m!jW8@{yOQBxnEi?azK^y+hxsiM7XB^y;qWWiD$^I)!wz<)XfKRf%4WbSaz1ZL&yxSe32J zZ7o^gRosbl4injtu=SOG!IqVTeTas?*R|>>u6;c0x!Xd4&jyC~bJ7Dc>ybSyD@2KJ zY&OM5i)2IJgEaD!N55_T*%-s?#6gM6%!omMWzPoe?BW(ync!qX=|1Ow{wadXee3NFk!g0 zxq6Z&CiGX5&&kO1K_6XG7LeeWa%;&5n4)rAm+=MqncFNb>@&N-zwZIVHrK-A)|;)4 zxP0QhX%$nbS7=^TMw*E= z^{CrL1~#PeM3sU*tRw>^YZy`&V$_&0sMVQR|2GS^T@&jaglloHcgZ!aSQ0)qWD953 zdF`{=m}mOvr!yUl1s?DkRJNjYpRTRGW+a_+4_a+jp_|}U$+;$h2yID*P5e|G>**TS z4X6yO66@X8o66YhDa`8qFf4?}p{eI-MUY5vx|j_Ootrp?UM(U+MH@>JOSFKsQ5{}K z=~Vns^5`Hv^>I6U9O;{TF=GR1;B-|B5A^qmKDV{m~y(O8a zx{G)xE zyiAu(@9Bxs?gOi*4UbvXH|J^2*?4C+UN_|*taeiw;FhYKF6ob>{u{e6tJxjH=)9Y1 zbT7R}}L3Q(){4kn6o(JRiznA+id7ua+XBy z*O=Js4rrW}h^*ZXdnTRrklj|)Euz#sF(u=ZY5;!zBi2CGVwi)uf~rpM@i-@}OI~?S zNaOljltzcSVVZ4-FvYoN$s-nsr5z^|yXkFf0PVIMRhtazsi%q(2 zS5f75hnp$Ck#$nqmnqr!;eH>dxw_)|dvr^|70y WQ7N1@nu@03m#Q1Tor3d6W&Q)^Q<9MY literal 0 HcmV?d00001 diff --git a/uMod2/uMod_GUI/config.gcc b/uMod2/uMod_GUI/config.gcc new file mode 100644 index 0000000..ac29dd2 --- /dev/null +++ b/uMod2/uMod_GUI/config.gcc @@ -0,0 +1,149 @@ +# ========================================================================= +# This configuration file was generated by +# Bakefile 0.2.8 (http://www.bakefile.org) +# Beware that all changes made to this file will be overwritten next +# time you run Bakefile! +# ========================================================================= + + +# ------------------------------------------------------------------------- +# These are configurable options: +# ------------------------------------------------------------------------- + +# Compiler flags to link shared library +#LINK_DLL_FLAGS ?= -shared +LINK_DLL_FLAGS ?= + +# Compiler flags to link loadable module +#LINK_MODULE_FLAGS ?= -shared +LINK_MODULE_FLAGS ?= + +# C compiler +CC = gcc + +# C++ compiler +CXX = g++ + +# Standard flags for CC +CFLAGS ?= + +# Standard flags for C++ +CXXFLAGS ?= -Wno-unused + +# Standard preprocessor flags (common for CC and CXX) +CPPFLAGS ?= + +# Standard linker flags +LDFLAGS ?= -static-libgcc -static-libstdc++ + +# The C preprocessor +CPP ?= $(CC) -E + +# What type of library to build? [0,1] +SHARED ?= 0 + +# Build wxUniversal instead of native port? [0,1] +WXUNIV ?= 0 + +# Compile Unicode build of wxWidgets? [0,1] +UNICODE ?= 1 + +# Use MSLU library when building Unicode version. [0,1] +MSLU ?= 0 + +# Type of compiled binaries [debug,release] +BUILD ?= release + +# Should debugging info be included in the executables? The default value +# "default" means that debug info will be included if BUILD=debug +# and not included if BUILD=release. [0,1,default] +DEBUG_INFO ?= 0 + +# Value of wxDEBUG_LEVEL. The default value is the same as 1 and means that all +# but expensive assert checks are enabled, use 0 to completely remove debugging +# code. [0,1,default] +DEBUG_FLAG ?= 0 + +# Multiple libraries or single huge monolithic one? [0,1] +MONOLITHIC ?= 0 + +# Build GUI libraries? [0,1] +USE_GUI ?= 1 + +# Build wxHTML library (USE_GUI must be 1)? [0,1] +USE_HTML ?= 1 + +# Build multimedia library (USE_GUI must be 1)? [0,1] +USE_MEDIA ?= 1 + +# Build wxXRC library (USE_GUI must be 1)? [0,1] +USE_XRC ?= 1 + +# Build wxAUI library (USE_GUI must be 1)? [0,1] +USE_AUI ?= 1 + +# Build wxRibbon library (USE_GUI must be 1)? [0,1] +USE_RIBBON ?= 1 + +# Build wxPropertyGrid library (USE_GUI must be 1)? [0,1] +USE_PROPGRID ?= 1 + +# Build wxRichTextCtrl library (USE_GUI must be 1)? [0,1] +USE_RICHTEXT ?= 1 + +# Build wxStyledTextCtrl library (USE_GUI must be 1)? [0,1] +USE_STC ?= 1 + +# Build OpenGL canvas library (USE_GUI must be 1)? [0,1] +USE_OPENGL ?= 1 + +# Build quality assurance classes library (USE_GUI must be 1)? [0,1] +USE_QA ?= 0 + +# Enable exceptions in compiled code. [0,1] +USE_EXCEPTIONS ?= 1 + +# Enable run-time type information (RTTI) in compiled code. [0,1] +USE_RTTI ?= 1 + +# Enable threading in compiled code. [0,1] +USE_THREADS ?= 1 + +# Enable wxCairoContext for platforms other than Linux/GTK. [0,1] +USE_CAIRO ?= 0 + +# Is this official build by wxWidgets developers? [0,1] +OFFICIAL_BUILD ?= 0 + +# Use this to name your customized DLLs differently +VENDOR ?= custom + +# +WX_FLAVOUR ?= + +# +WX_LIB_FLAVOUR ?= + +# Name of your custom configuration. This affects directory +# where object files are stored as well as the location of +# compiled .lib files and setup.h under the lib/ toplevel directory. +CFG ?= + +# Compiler flags needed to compile test suite in tests directory. If you want +# to run the tests, set it so that the compiler can find CppUnit headers. +CPPUNIT_CFLAGS ?= + +# Linker flags needed to link test suite in tests directory. If you want +# to run the tests, include CppUnit library here. +CPPUNIT_LIBS ?= + +# Version of C runtime library to use. You can change this to +# static if SHARED=0, but it is highly recommended to not do +# it if SHARED=1 unless you know what you are doing. [dynamic,static] +RUNTIME_LIBS ?= static + +# Set the version of your Mingw installation here. +# "3" ...... this is for Mingw 2.0 or newer (comes with gcc3) +# "2.95" ... for Mingw 1.1 or any of the older versions [3,2.95] +GCC_VERSION ?= 3 + diff --git a/uMod2/uMod_GUI/config.vc b/uMod2/uMod_GUI/config.vc new file mode 100644 index 0000000..aa404c3 --- /dev/null +++ b/uMod2/uMod_GUI/config.vc @@ -0,0 +1,149 @@ +# ========================================================================= +# This configuration file was generated by +# Bakefile 0.2.8 (http://www.bakefile.org) +# Beware that all changes made to this file will be overwritten next +# time you run Bakefile! +# ========================================================================= + + +# ------------------------------------------------------------------------- +# These are configurable options: +# ------------------------------------------------------------------------- + +# C compiler +CC = cl + +# C++ compiler +CXX = cl + +# Standard flags for CC +CFLAGS = + +# Standard flags for C++ +CXXFLAGS = + +# Standard preprocessor flags (common for CC and CXX) +CPPFLAGS = + +# Standard linker flags +LDFLAGS = + +# The C preprocessor +CPP = $(CC) /EP /nologo + +# What type of library to build? [0,1] +SHARED = 0 + +# Build wxUniversal instead of native port? [0,1] +WXUNIV = 0 + +# Compile Unicode build of wxWidgets? [0,1] +UNICODE = 1 + +# Use MSLU library when building Unicode version. [0,1] +MSLU = 0 + +# Type of compiled binaries [debug,release] +BUILD = release + +# The target processor architecture must be specified when it is not X86. +# This does not affect the compiler output, so you still need to make sure +# your environment is set up appropriately with the correct compiler in the +# PATH. Rather it affects some options passed to some of the common build +# utilities such as the resource compiler and the linker. +# +# Accepted values: AMD64, IA64. +TARGET_CPU = $(CPU) + +# Should debugging info be included in the executables? The default value +# "default" means that debug info will be included if BUILD=debug +# and not included if BUILD=release. [0,1,default] +DEBUG_INFO = 1 + +# Value of wxDEBUG_LEVEL. The default value is the same as 1 and means that all +# but expensive assert checks are enabled, use 0 to completely remove debugging +# code. [0,1,default] +DEBUG_FLAG = 0 + +# Link against debug (e.g. msvcrtd.dll) or release (msvcrt.dll) RTL? +# Default is to use debug CRT if and only if BUILD==debug. [0,1,default] +DEBUG_RUNTIME_LIBS = default + +# Multiple libraries or single huge monolithic one? [0,1] +MONOLITHIC = 0 + +# Build GUI libraries? [0,1] +USE_GUI = 1 + +# Build wxHTML library (USE_GUI must be 1)? [0,1] +USE_HTML = 1 + +# Build multimedia library (USE_GUI must be 1)? [0,1] +USE_MEDIA = 1 + +# Build wxXRC library (USE_GUI must be 1)? [0,1] +USE_XRC = 1 + +# Build wxAUI library (USE_GUI must be 1)? [0,1] +USE_AUI = 1 + +# Build wxRibbon library (USE_GUI must be 1)? [0,1] +USE_RIBBON = 1 + +# Build wxPropertyGrid library (USE_GUI must be 1)? [0,1] +USE_PROPGRID = 1 + +# Build wxRichTextCtrl library (USE_GUI must be 1)? [0,1] +USE_RICHTEXT = 1 + +# Build wxStyledTextCtrl library (USE_GUI must be 1)? [0,1] +USE_STC = 1 + +# Build OpenGL canvas library (USE_GUI must be 1)? [0,1] +USE_OPENGL = 1 + +# Build quality assurance classes library (USE_GUI must be 1)? [0,1] +USE_QA = 1 + +# Enable exceptions in compiled code. [0,1] +USE_EXCEPTIONS = 1 + +# Enable run-time type information (RTTI) in compiled code. [0,1] +USE_RTTI = 1 + +# Enable threading in compiled code. [0,1] +USE_THREADS = 1 + +# Enable wxCairoContext for platforms other than Linux/GTK. [0,1] +USE_CAIRO = 0 + +# Is this official build by wxWidgets developers? [0,1] +OFFICIAL_BUILD = 0 + +# Use this to name your customized DLLs differently +VENDOR = custom + +# +WX_FLAVOUR = + +# +WX_LIB_FLAVOUR = + +# Name of your custom configuration. This affects directory +# where object files are stored as well as the location of +# compiled .lib files and setup.h under the lib/ toplevel directory. +CFG = + +# Compiler flags needed to compile test suite in tests directory. If you want +# to run the tests, set it so that the compiler can find CppUnit headers. +CPPUNIT_CFLAGS = + +# Linker flags needed to link test suite in tests directory. If you want +# to run the tests, include CppUnit library here. +CPPUNIT_LIBS = + +# Version of C runtime library to use. You can change this to +# static if SHARED=0, but it is highly recommended to not do +# it if SHARED=1 unless you know what you are doing. [dynamic,static] +RUNTIME_LIBS = static + diff --git a/uMod2/uMod_GUI/makefile.gcc b/uMod2/uMod_GUI/makefile.gcc new file mode 100644 index 0000000..eb90f0c --- /dev/null +++ b/uMod2/uMod_GUI/makefile.gcc @@ -0,0 +1,284 @@ +# ========================================================================= +# This makefile was generated by +# Bakefile 0.2.1 (http://bakefile.sourceforge.net) +# Do not modify, all changes will be overwritten! +# ========================================================================= + +include config.gcc + +# ------------------------------------------------------------------------- +# Do not modify the rest of this file! +# ------------------------------------------------------------------------- + +### Variables: ### + +CPPDEPS = -MT$@ -MF$@.d -MD +WX_RELEASE_NODOT = 29 +OBJS = \ + obj +OBJS_exe = \ + bin +WX_DIR = D:\Programme\wxWidgets-2.9.2 +LIBDIRNAME = $(WX_DIR)\lib\gcc_$(LIBTYPE_SUFFIX)$(CFG) +SETUPHDIR = \ + $(LIBDIRNAME)\$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG) +MINIMAL_CXXFLAGS = $(__DEBUGINFO) $(__OPTIMIZEFLAG_2) $(__THREADSFLAG) \ + $(GCCFLAGS) -DHAVE_W32API_H -D__WXMSW__ $(__WXUNIV_DEFINE_p) \ + $(__DEBUG_DEFINE_p) $(__EXCEPTIONS_DEFINE_p) $(__RTTI_DEFINE_p) \ + $(__THREAD_DEFINE_p) $(__UNICODE_DEFINE_p) $(__MSLU_DEFINE_p) \ + $(__GFXCTX_DEFINE_p) -I$(SETUPHDIR) -I$(WX_DIR)\include -W -Wall -Wextra -I. \ + $(__DLLFLAG_p) -DNOPCH $(__RTTIFLAG_5) \ + $(__EXCEPTIONSFLAG_6) -Wno-ctor-dtor-privacy $(CPPFLAGS) $(CXXFLAGS) +MINIMAL_OBJECTS = \ + $(OBJS)\uMod_rc.o \ + $(OBJS)\unzip.o \ + $(OBJS)\uMod_DirectInjection.o \ + $(OBJS)\uMod_GUI.o \ + $(OBJS)\uMod_GameInfo.o \ + $(OBJS)\uMod_GamePage.o \ + $(OBJS)\uMod_Server.o \ + $(OBJS)\uMod_Client.o \ + $(OBJS)\uMod_File.o \ + $(OBJS)\uMod_Sender.o \ + $(OBJS)\uMod_Settings.o \ + $(OBJS)\uMod_AddTexture.o \ + $(OBJS)\uMod_Language.o + +### Conditionally set variables: ### + +ifeq ($(GCC_VERSION),2.95) +GCCFLAGS = -fvtable-thunks +endif +ifeq ($(USE_GUI),0) +PORTNAME = base +endif +ifeq ($(USE_GUI),1) +PORTNAME = msw +endif +ifeq ($(BUILD),debug) +ifeq ($(DEBUG_FLAG),default) +WXDEBUGFLAG = d +endif +endif +ifeq ($(DEBUG_FLAG),1) +WXDEBUGFLAG = d +endif +ifeq ($(UNICODE),1) +WXUNICODEFLAG = u +endif +ifeq ($(WXUNIV),1) +WXUNIVNAME = univ +endif +ifeq ($(SHARED),1) +WXDLLFLAG = dll +endif +ifeq ($(SHARED),0) +LIBTYPE_SUFFIX = lib +endif +ifeq ($(SHARED),1) +LIBTYPE_SUFFIX = dll +endif +ifeq ($(MONOLITHIC),0) +EXTRALIBS_FOR_BASE = +endif +ifeq ($(MONOLITHIC),1) +EXTRALIBS_FOR_BASE = +endif +ifeq ($(BUILD),debug) +__OPTIMIZEFLAG_2 = -O0 -g +endif +ifeq ($(BUILD),release) +__OPTIMIZEFLAG_2 = -O2 +endif +ifeq ($(USE_RTTI),0) +__RTTIFLAG_5 = -fno-rtti +endif +ifeq ($(USE_RTTI),1) +__RTTIFLAG_5 = +endif +ifeq ($(USE_EXCEPTIONS),0) +__EXCEPTIONSFLAG_6 = -fno-exceptions +endif +ifeq ($(USE_EXCEPTIONS),1) +__EXCEPTIONSFLAG_6 = +endif +ifeq ($(WXUNIV),1) +__WXUNIV_DEFINE_p = -D__WXUNIVERSAL__ +endif +ifeq ($(WXUNIV),1) +__WXUNIV_DEFINE_p_1 = --define __WXUNIVERSAL__ +endif +ifeq ($(BUILD),debug) +ifeq ($(DEBUG_FLAG),default) +__DEBUG_DEFINE_p = -D__WXDEBUG__ +endif +endif +ifeq ($(DEBUG_FLAG),1) +__DEBUG_DEFINE_p = -D__WXDEBUG__ +endif +ifeq ($(BUILD),debug) +ifeq ($(DEBUG_FLAG),default) +__DEBUG_DEFINE_p_1 = --define __WXDEBUG__ +endif +endif +ifeq ($(DEBUG_FLAG),1) +__DEBUG_DEFINE_p_1 = --define __WXDEBUG__ +endif +ifeq ($(USE_EXCEPTIONS),0) +__EXCEPTIONS_DEFINE_p = -DwxNO_EXCEPTIONS +endif +ifeq ($(USE_EXCEPTIONS),0) +__EXCEPTIONS_DEFINE_p_1 = --define wxNO_EXCEPTIONS +endif +ifeq ($(USE_RTTI),0) +__RTTI_DEFINE_p = -DwxNO_RTTI +endif +ifeq ($(USE_RTTI),0) +__RTTI_DEFINE_p_1 = --define wxNO_RTTI +endif +ifeq ($(USE_THREADS),0) +__THREAD_DEFINE_p = -DwxNO_THREADS +endif +ifeq ($(USE_THREADS),0) +__THREAD_DEFINE_p_1 = --define wxNO_THREADS +endif +ifeq ($(UNICODE),1) +__UNICODE_DEFINE_p = -D_UNICODE +endif +ifeq ($(UNICODE),1) +__UNICODE_DEFINE_p_1 = --define _UNICODE +endif +ifeq ($(MSLU),1) +__MSLU_DEFINE_p = -DwxUSE_UNICODE_MSLU=1 +endif +ifeq ($(MSLU),1) +__MSLU_DEFINE_p_1 = --define wxUSE_UNICODE_MSLU=1 +endif +ifeq ($(USE_GDIPLUS),1) +__GFXCTX_DEFINE_p = -DwxUSE_GRAPHICS_CONTEXT=1 +endif +ifeq ($(USE_GDIPLUS),1) +__GFXCTX_DEFINE_p_1 = --define wxUSE_GRAPHICS_CONTEXT=1 +endif +ifeq ($(SHARED),1) +__DLLFLAG_p = -DWXUSINGDLL +endif +ifeq ($(SHARED),1) +__DLLFLAG_p_1 = --define WXUSINGDLL +endif +ifeq ($(MONOLITHIC),0) +__WXLIB_CORE_p = \ + -lwx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_core +endif +ifeq ($(MONOLITHIC),0) +__WXLIB_BASE_p = \ + -lwxbase$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR) +endif +ifeq ($(MONOLITHIC),1) +__WXLIB_MONO_p = \ + -lwx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR) +endif +ifeq ($(USE_GUI),1) +__LIB_TIFF_p = -lwxtiff$(WXDEBUGFLAG) +endif +ifeq ($(USE_GUI),1) +__LIB_JPEG_p = -lwxjpeg$(WXDEBUGFLAG) +endif +ifeq ($(USE_GUI),1) +__LIB_PNG_p = -lwxpng$(WXDEBUGFLAG) +endif +ifeq ($(MSLU),1) +__UNICOWS_LIB_p = -lunicows +endif +ifeq ($(USE_GDIPLUS),1) +__GDIPLUS_LIB_p = -lgdiplus +endif +ifeq ($(BUILD),debug) +ifeq ($(DEBUG_INFO),default) +__DEBUGINFO = -g +endif +endif +ifeq ($(BUILD),release) +ifeq ($(DEBUG_INFO),default) +__DEBUGINFO = +endif +endif +ifeq ($(DEBUG_INFO),0) +__DEBUGINFO = +endif +ifeq ($(DEBUG_INFO),1) +__DEBUGINFO = -g +endif +ifeq ($(USE_THREADS),0) +__THREADSFLAG = +endif +ifeq ($(USE_THREADS),1) +__THREADSFLAG = -mthreads +endif + + +all: $(OBJS) +$(OBJS): + -if not exist $(OBJS) mkdir $(OBJS) + +all: $(OBJS_exe) +$(OBJS_exe): + -if not exist $(OBJS_exe) mkdir $(OBJS_exe) + +### Targets: ### + +all: $(OBJS_exe)\uMod.exe + +clean: + -if exist $(OBJS)\*.o del $(OBJS)\*.o + -if exist $(OBJS)\*.d del $(OBJS)\*.d + -if exist $(OBJS_exe)\uMod.exe del $(OBJS_exe)\uMod.exe + +$(OBJS_exe)\uMod.exe: $(MINIMAL_OBJECTS) $(OBJS)\uMod_rc.o + $(CXX) -o $@ $(MINIMAL_OBJECTS) $(LDFLAGS) $(__DEBUGINFO) $(__THREADSFLAG) -L$(LIBDIRNAME) -Wl,--subsystem,windows -mwindows $(__WXLIB_CORE_p) $(__WXLIB_BASE_p) $(__WXLIB_MONO_p) $(__LIB_TIFF_p) $(__LIB_JPEG_p) $(__LIB_PNG_p) -lwxzlib$(WXDEBUGFLAG) -lwxregex$(WXUNICODEFLAG)$(WXDEBUGFLAG) -lwxexpat$(WXDEBUGFLAG) $(EXTRALIBS_FOR_BASE) $(__UNICOWS_LIB_p) $(__GDIPLUS_LIB_p) -lkernel32 -luser32 -lgdi32 -lcomdlg32 -lwinspool -lwinmm -lshell32 -lcomctl32 -lole32 -loleaut32 -luuid -lrpcrt4 -ladvapi32 -lwsock32 -lodbc32 + +$(OBJS)\uMod_rc.o: uMod.rc uMod.ico + windres --use-temp-file -i $< -o $@ + +$(OBJS)\unzip.o: ./unzip.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_DirectInjection.o: ./uMod_DirectInjection.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_GUI.o: ./uMod_GUI.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_GameInfo.o: ./uMod_GameInfo.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_GamePage.o: ./uMod_GamePage.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_Server.o: ./uMod_Server.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_Client.o: ./uMod_Client.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_File.o: ./uMod_File.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_Sender.o: ./uMod_Sender.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_Settings.o: ./uMod_Settings.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_AddTexture.o: ./uMod_AddTexture.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + +$(OBJS)\uMod_Language.o: ./uMod_Language.cpp + $(CXX) -c -o $@ $(MINIMAL_CXXFLAGS) $(CPPDEPS) $< + + +.PHONY: all clean + + +# Dependencies tracking: +-include $(OBJS)/*.d diff --git a/uMod2/uMod_GUI/makefile.vc b/uMod2/uMod_GUI/makefile.vc new file mode 100644 index 0000000..94e7dae --- /dev/null +++ b/uMod2/uMod_GUI/makefile.vc @@ -0,0 +1,401 @@ +# ========================================================================= +# This makefile was generated by +# Bakefile 0.2.8 (http://www.bakefile.org) +# Do not modify, all changes will be overwritten! +# ========================================================================= + +!include + +# ------------------------------------------------------------------------- +# Do not modify the rest of this file! +# ------------------------------------------------------------------------- + +### Variables: ### + +WX_RELEASE_NODOT = 29 +COMPILER_PREFIX = vc +OBJS = \ + obj +OBJS_exe = \ + bin +WX_DIR = D:\Programme\wxWidgets-2.9.2 +LIBDIRNAME = \ + $(WX_DIR)\lib\$(COMPILER_PREFIX)$(DIR_SUFFIX_CPU)_$(LIBTYPE_SUFFIX)$(CFG) +SETUPHDIR = \ + $(LIBDIRNAME)\$(PORTNAME)$(WXUNIVNAME)$(WXUNICODEFLAG)$(WXDEBUGFLAG) +MINIMAL_CXXFLAGS = /M$(__RUNTIME_LIBS_10)$(__DEBUGRUNTIME_4) /DWIN32 \ + $(__DEBUGINFO_0) /Fd$(OBJS)\uMod_GUI.pdb $(____DEBUGRUNTIME_3_p) \ + $(__OPTIMIZEFLAG_6) $(__NO_VC_CRTDBG_p) /D__WXMSW__ $(__WXUNIV_DEFINE_p) \ + $(__DEBUG_DEFINE_p) $(__NDEBUG_DEFINE_p) $(__EXCEPTIONS_DEFINE_p) \ + $(__RTTI_DEFINE_p) $(__THREAD_DEFINE_p) $(__UNICODE_DEFINE_p) \ + $(__MSLU_DEFINE_p) /I$(SETUPHDIR) /I$(WX_DIR)\include \ + $(____CAIRO_INCLUDEDIR_FILENAMES_p) /W4 /I. $(__DLLFLAG_p) /D_WINDOWS \ + /DNOPCH $(__RTTIFLAG_11) $(__EXCEPTIONSFLAG_12) \ + $(CPPFLAGS) $(CXXFLAGS) +MINIMAL_OBJECTS = \ + $(OBJS)\unzip.obj \ + $(OBJS)\uMod_DirectInjection.obj \ + $(OBJS)\uMod_GUI.obj \ + $(OBJS)\uMod_GameInfo.obj \ + $(OBJS)\uMod_GamePage.obj \ + $(OBJS)\uMod_Server.obj \ + $(OBJS)\uMod_Client.obj \ + $(OBJS)\uMod_File.obj \ + $(OBJS)\uMod_Sender.obj \ + $(OBJS)\uMod_Settings.obj \ + $(OBJS)\uMod_AddTexture.obj \ + $(OBJS)\uMod_Language.obj +MINIMAL_RESOURCES = \ + $(OBJS)\uMod_GUI.res + +### Conditionally set variables: ### + +!if "$(USE_GUI)" == "0" +PORTNAME = base +!endif +!if "$(USE_GUI)" == "1" +PORTNAME = msw +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "default" +WXDEBUGFLAG = d +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "1" +WXDEBUGFLAG = d +!endif +!if "$(UNICODE)" == "1" +WXUNICODEFLAG = u +!endif +!if "$(WXUNIV)" == "1" +WXUNIVNAME = univ +!endif +!if "$(TARGET_CPU)" == "AMD64" +DIR_SUFFIX_CPU = _amd64 +!endif +!if "$(TARGET_CPU)" == "IA64" +DIR_SUFFIX_CPU = _ia64 +!endif +!if "$(TARGET_CPU)" == "amd64" +DIR_SUFFIX_CPU = _amd64 +!endif +!if "$(TARGET_CPU)" == "ia64" +DIR_SUFFIX_CPU = _ia64 +!endif +!if "$(SHARED)" == "1" +WXDLLFLAG = dll +!endif +!if "$(SHARED)" == "0" +LIBTYPE_SUFFIX = lib +!endif +!if "$(SHARED)" == "1" +LIBTYPE_SUFFIX = dll +!endif +!if "$(TARGET_CPU)" == "AMD64" +LINK_TARGET_CPU = /MACHINE:X64 +!endif +!if "$(TARGET_CPU)" == "IA64" +LINK_TARGET_CPU = /MACHINE:IA64 +!endif +!if "$(TARGET_CPU)" == "amd64" +LINK_TARGET_CPU = /MACHINE:X64 +!endif +!if "$(TARGET_CPU)" == "ia64" +LINK_TARGET_CPU = /MACHINE:IA64 +!endif +!if "$(MONOLITHIC)" == "0" +EXTRALIBS_FOR_BASE = +!endif +!if "$(MONOLITHIC)" == "1" +EXTRALIBS_FOR_BASE = +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_0 = /Zi +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_0 = +!endif +!if "$(DEBUG_INFO)" == "0" +__DEBUGINFO_0 = +!endif +!if "$(DEBUG_INFO)" == "1" +__DEBUGINFO_0 = /Zi +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_1 = /DEBUG +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_1 = +!endif +!if "$(DEBUG_INFO)" == "0" +__DEBUGINFO_1 = +!endif +!if "$(DEBUG_INFO)" == "1" +__DEBUGINFO_1 = /DEBUG +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_2 = $(__DEBUGRUNTIME_5) +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_INFO)" == "default" +__DEBUGINFO_2 = +!endif +!if "$(DEBUG_INFO)" == "0" +__DEBUGINFO_2 = +!endif +!if "$(DEBUG_INFO)" == "1" +__DEBUGINFO_2 = $(__DEBUGRUNTIME_5) +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "default" +____DEBUGRUNTIME_3_p = /D_DEBUG +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +____DEBUGRUNTIME_3_p = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +____DEBUGRUNTIME_3_p = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "1" +____DEBUGRUNTIME_3_p = /D_DEBUG +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "default" +____DEBUGRUNTIME_3_p_1 = /d _DEBUG +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +____DEBUGRUNTIME_3_p_1 = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +____DEBUGRUNTIME_3_p_1 = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "1" +____DEBUGRUNTIME_3_p_1 = /d _DEBUG +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__DEBUGRUNTIME_4 = d +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__DEBUGRUNTIME_4 = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +__DEBUGRUNTIME_4 = +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "1" +__DEBUGRUNTIME_4 = d +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__DEBUGRUNTIME_5 = +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__DEBUGRUNTIME_5 = /opt:ref /opt:icf +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +__DEBUGRUNTIME_5 = /opt:ref /opt:icf +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "1" +__DEBUGRUNTIME_5 = +!endif +!if "$(BUILD)" == "debug" +__OPTIMIZEFLAG_6 = /Od +!endif +!if "$(BUILD)" == "release" +__OPTIMIZEFLAG_6 = /O2 +!endif +!if "$(USE_THREADS)" == "0" +__THREADSFLAG_9 = L +!endif +!if "$(USE_THREADS)" == "1" +__THREADSFLAG_9 = T +!endif +!if "$(RUNTIME_LIBS)" == "dynamic" +__RUNTIME_LIBS_10 = D +!endif +!if "$(RUNTIME_LIBS)" == "static" +__RUNTIME_LIBS_10 = $(__THREADSFLAG_9) +!endif +!if "$(USE_RTTI)" == "0" +__RTTIFLAG_11 = +!endif +!if "$(USE_RTTI)" == "1" +__RTTIFLAG_11 = /GR +!endif +!if "$(USE_EXCEPTIONS)" == "0" +__EXCEPTIONSFLAG_12 = +!endif +!if "$(USE_EXCEPTIONS)" == "1" +__EXCEPTIONSFLAG_12 = /EHsc +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "0" +__NO_VC_CRTDBG_p = /D__NO_VC_CRTDBG__ +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_FLAG)" == "1" +__NO_VC_CRTDBG_p = /D__NO_VC_CRTDBG__ +!endif +!if "$(BUILD)" == "debug" && "$(DEBUG_RUNTIME_LIBS)" == "0" +__NO_VC_CRTDBG_p_1 = /d __NO_VC_CRTDBG__ +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_FLAG)" == "1" +__NO_VC_CRTDBG_p_1 = /d __NO_VC_CRTDBG__ +!endif +!if "$(WXUNIV)" == "1" +__WXUNIV_DEFINE_p = /D__WXUNIVERSAL__ +!endif +!if "$(WXUNIV)" == "1" +__WXUNIV_DEFINE_p_1 = /d __WXUNIVERSAL__ +!endif +!if "$(DEBUG_FLAG)" == "0" +__DEBUG_DEFINE_p = /DwxDEBUG_LEVEL=0 +!endif +!if "$(DEBUG_FLAG)" == "0" +__DEBUG_DEFINE_p_1 = /d wxDEBUG_LEVEL=0 +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__NDEBUG_DEFINE_p = /DNDEBUG +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +__NDEBUG_DEFINE_p = /DNDEBUG +!endif +!if "$(BUILD)" == "release" && "$(DEBUG_RUNTIME_LIBS)" == "default" +__NDEBUG_DEFINE_p_1 = /d NDEBUG +!endif +!if "$(DEBUG_RUNTIME_LIBS)" == "0" +__NDEBUG_DEFINE_p_1 = /d NDEBUG +!endif +!if "$(USE_EXCEPTIONS)" == "0" +__EXCEPTIONS_DEFINE_p = /DwxNO_EXCEPTIONS +!endif +!if "$(USE_EXCEPTIONS)" == "0" +__EXCEPTIONS_DEFINE_p_1 = /d wxNO_EXCEPTIONS +!endif +!if "$(USE_RTTI)" == "0" +__RTTI_DEFINE_p = /DwxNO_RTTI +!endif +!if "$(USE_RTTI)" == "0" +__RTTI_DEFINE_p_1 = /d wxNO_RTTI +!endif +!if "$(USE_THREADS)" == "0" +__THREAD_DEFINE_p = /DwxNO_THREADS +!endif +!if "$(USE_THREADS)" == "0" +__THREAD_DEFINE_p_1 = /d wxNO_THREADS +!endif +!if "$(UNICODE)" == "0" +__UNICODE_DEFINE_p = /DwxUSE_UNICODE=0 +!endif +!if "$(UNICODE)" == "1" +__UNICODE_DEFINE_p = /D_UNICODE +!endif +!if "$(UNICODE)" == "0" +__UNICODE_DEFINE_p_1 = /d wxUSE_UNICODE=0 +!endif +!if "$(UNICODE)" == "1" +__UNICODE_DEFINE_p_1 = /d _UNICODE +!endif +!if "$(MSLU)" == "1" +__MSLU_DEFINE_p = /DwxUSE_UNICODE_MSLU=1 +!endif +!if "$(MSLU)" == "1" +__MSLU_DEFINE_p_1 = /d wxUSE_UNICODE_MSLU=1 +!endif +!if "$(USE_CAIRO)" == "1" +____CAIRO_INCLUDEDIR_FILENAMES_p = /I$(CAIRO_ROOT)\include\cairo +!endif +!if "$(USE_CAIRO)" == "1" +____CAIRO_INCLUDEDIR_FILENAMES_1_p = /i $(CAIRO_ROOT)\include\cairo +!endif +!if "$(SHARED)" == "1" +__DLLFLAG_p = /DWXUSINGDLL +!endif +!if "$(SHARED)" == "1" +__DLLFLAG_p_1 = /d WXUSINGDLL +!endif +!if "$(MONOLITHIC)" == "0" +__WXLIB_CORE_p = \ + wx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR)_core.lib +!endif +!if "$(MONOLITHIC)" == "0" +__WXLIB_BASE_p = \ + wxbase$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR).lib +!endif +!if "$(MONOLITHIC)" == "1" +__WXLIB_MONO_p = \ + wx$(PORTNAME)$(WXUNIVNAME)$(WX_RELEASE_NODOT)$(WXUNICODEFLAG)$(WXDEBUGFLAG)$(WX_LIB_FLAVOUR).lib +!endif +!if "$(USE_GUI)" == "1" +__LIB_TIFF_p = wxtiff$(WXDEBUGFLAG).lib +!endif +!if "$(USE_GUI)" == "1" +__LIB_JPEG_p = wxjpeg$(WXDEBUGFLAG).lib +!endif +!if "$(USE_GUI)" == "1" +__LIB_PNG_p = wxpng$(WXDEBUGFLAG).lib +!endif +!if "$(MSLU)" == "1" +__UNICOWS_LIB_p = unicows.lib +!endif +!if "$(USE_CAIRO)" == "1" +__CAIRO_LIB_p = cairo.lib +!endif +!if "$(USE_CAIRO)" == "1" +____CAIRO_LIBDIR_FILENAMES_p = /LIBPATH:$(CAIRO_ROOT)\lib +!endif + + +all: $(OBJS) +$(OBJS): + -if not exist $(OBJS) mkdir $(OBJS) + +### Targets: ### + +all: $(OBJS_exe)\uMod.exe + +clean: + -if exist $(OBJS)\*.obj del $(OBJS)\*.obj + -if exist $(OBJS)\*.res del $(OBJS)\*.res + -if exist $(OBJS)\*.pch del $(OBJS)\*.pch + -if exist $(OBJS_exe)\uMod_GUI.exe del $(OBJS_exe)\uMod.exe + -if exist $(OBJS_exe)\uMod_GUI.ilk del $(OBJS_exe)\uMod_GUI.ilk + -if exist $(OBJS_exe)\uMod_GUI.pdb del $(OBJS_exe)\uMod_GUI.pdb + +$(OBJS_exe)\uMod.exe: $(MINIMAL_OBJECTS) $(OBJS)\uMod_GUI.res + link /NOLOGO /OUT:$@ $(__DEBUGINFO_1) /pdb:"$(OBJS)\uMod_GUI.pdb" $(__DEBUGINFO_2) $(LINK_TARGET_CPU) /LIBPATH:$(LIBDIRNAME) /SUBSYSTEM:WINDOWS $(____CAIRO_LIBDIR_FILENAMES_p) $(LDFLAGS) @<< + $(MINIMAL_OBJECTS) $(MINIMAL_RESOURCES) $(__WXLIB_CORE_p) $(__WXLIB_BASE_p) $(__WXLIB_MONO_p) $(__LIB_TIFF_p) $(__LIB_JPEG_p) $(__LIB_PNG_p) wxzlib$(WXDEBUGFLAG).lib wxregex$(WXUNICODEFLAG)$(WXDEBUGFLAG).lib wxexpat$(WXDEBUGFLAG).lib $(EXTRALIBS_FOR_BASE) $(__UNICOWS_LIB_p) $(__CAIRO_LIB_p) kernel32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib winmm.lib shell32.lib comctl32.lib ole32.lib oleaut32.lib uuid.lib rpcrt4.lib advapi32.lib wsock32.lib wininet.lib +<< + +$(OBJS)\uMod_GUI.res: uMod.rc + rc /fo$@ /d WIN32 $(____DEBUGRUNTIME_3_p_1) $(__NO_VC_CRTDBG_p_1) /d __WXMSW__ $(__WXUNIV_DEFINE_p_1) $(__DEBUG_DEFINE_p_1) $(__NDEBUG_DEFINE_p_1) $(__EXCEPTIONS_DEFINE_p_1) $(__RTTI_DEFINE_p_1) $(__THREAD_DEFINE_p_1) $(__UNICODE_DEFINE_p_1) $(__MSLU_DEFINE_p_1) /i $(SETUPHDIR) /i . $(__DLLFLAG_p_1) /d _WINDOWS /d NOPCH uMod.rc + +#$(OBJS)\display_display.obj: .\display.cpp +# $(CXX) /c /nologo /TP /Fo$@ $(DISPLAY_CXXFLAGS) .\display.cpp + +$(OBJS)\unzip.obj: .\unzip.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\unzip.cpp + +$(OBJS)\uMod_DirectInjection.obj: .\uMod_DirectInjection.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_DirectInjection.cpp + +$(OBJS)\uMod_GUI.obj: .\uMod_GUI.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_GUI.cpp + +$(OBJS)\uMod_GameInfo.obj: .\uMod_GameInfo.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_GameInfo.cpp + +$(OBJS)\uMod_GamePage.obj: .\uMod_GamePage.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_GamePage.cpp + +$(OBJS)\uMod_Server.obj: .\uMod_Server.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_Server.cpp + +$(OBJS)\uMod_Client.obj: .\uMod_Client.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_Client.cpp + +$(OBJS)\uMod_File.obj: .\uMod_File.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_File.cpp + +$(OBJS)\uMod_Sender.obj: .\uMod_Sender.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_Sender.cpp + +$(OBJS)\uMod_Settings.obj: .\uMod_Settings.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_Settings.cpp + +$(OBJS)\uMod_AddTexture.obj: .\uMod_AddTexture.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_AddTexture.cpp + +$(OBJS)\uMod_Language.obj: .\uMod_Language.cpp + $(CXX) /c /nologo /TP /Fo$@ $(MINIMAL_CXXFLAGS) .\uMod_Language.cpp diff --git a/uMod2/uMod_GUI/uMod.ico b/uMod2/uMod_GUI/uMod.ico new file mode 100644 index 0000000000000000000000000000000000000000..610925e8de420f64c8103473e69b60e8fe70c107 GIT binary patch literal 20462 zcmeHNTWDNW6utG;)(5p}rJ^*Wf)A+pK(T7fwBVBpMFa(*AnK1Fia`V)m_+kYA(~Kp zfcg^!HQ?*Riu%)}RuWMZ6$(*XJ54?;STyySR&88sGJEdInRCy~6&f?c*=5bycdxbg zJ!j8-oRU?f!hI5`^C7sU4v)U{hP1o>U7F656xd$Om{GQ`M*a>?~M8f?~>)~F#7*a)b`{A+z;N9&Wk<7nQ% zb~|uf1y^BY%=W|aZNRnX5HQU@@HYeJ0zCc;Ko7uk%l-Zksxhm>(PuiJPa!bF7k_gSc39}bk~t{La6HwLlsp?izfyj}F8 z7R0z!;x|j&=klDjefs9aoDi?)To1*tF2Hi0C`aag80XvHKFM7*H_f|srs(&IVwc3v zkhss~YlYC9m=of8yc>Tp#jpzii+xp&%>6KqqicG7TI`aZ?PC$Mdeg%HCh>Z8c>l5* zzB#dM7SA;sw}(Qpo$!q-NSv<4Il7j&2V9@k3q$%;E9PXGt?( zJ>z(PGk&WD1LKJ3`$ebE4zEbu=YAkHbd9RDIVpdSK-z} zGd_lx*1AYEtA*or;s)W=y-RdfOL_B+<7oCi9E)civ)r#~-m*lAX+5D6YAuiBn?O5o zJizN0eLfqjW(eD^>G#WfMi)>3cpW_-*bE#3v<`irsfIk~!kUcpdHV#wXS^Qo2dLw{ zY6(Dd>&-^fPyYS$t)tT%*WUr{@-)5b@!4S?;OgCN_E=-p0^+#*Et11thwOEbmcPCt zv~7-AwgSW!K(#*qJ!sgoEV~fIF2I+|*a*PCFO|n;jk)~GP*{xDg^=+)G3|>Lp>1=l zXKNuC1ik}!&p!z426zp+4rs)9{M`q94Dh&QoiBlV0eg0+Hz(!!PR8!xJePQX2pP{4 zJ8$;F=lw$Kg>vVUt2Za*ua-6N@8m{IkLfFrp!FKbpASvFIVs;KYk0K5$=xkEPm0gF z3&nJezBwuX4FtBm+9&qJ_;(ra(aamKj8+4i3&LzZ9DSy|`MlQVv5z3OTpjb&IGoyg zb5h=XeJ*WeZk;XIgJL5K7fqqbdmu}RZtOtpKuRV2C@|3yT_LRzJs#gDNK)0OV|#q!qzktSP|c$9}q2bTE%|F zLaYb;{zLXONYl1b59~cF*K}g20pQlOXb<#z4{4i;%d;l-D388b`jB@` zdG*cEhrDabtB*Zsh7ROEzvFR`zh}*GB;@^G^Xg*{nxO;vkL`FI-LK zu>-LKu>-LKu>-LKu>-LKu>(!mftiZ+VD5**pPW8aEOk$Jvi{^$SFxw9wA}n;*~p@b z-?40Q@8e~^)X`BK8`x9!Cpy}T+f%=LvTc7kzI|1D)gNoXALvi@@T)Zk`qO>2jbaX) zX6Mj0TCC0uzRh`}I8j{-ee|n5AN5P!Q`LC3Kb>l3QXloo#x?$r{?r=myfTN<%G4iO blKQ. +*/ + + + +#include "uMod_Main.h" + + + +AddTextureClass::AddTextureClass(void) +{ + Num = 0; + Textures = NULL; + Size = NULL; + Hash = NULL; + WasAdded = NULL; + Len=0; + + Add = false; + Force = false; + Loaded = false; + OwnMemory = false; +} + +AddTextureClass::~AddTextureClass(void) +{ + ReleaseMemory(); +} + +int AddTextureClass::ReleaseMemory(void) +{ + if (OwnMemory) + { + if (Size!=NULL) delete [] Size; + if (Hash!=NULL) delete [] Hash; + if (WasAdded!=NULL) delete [] WasAdded; + + + if (Textures!=NULL) + { + for (unsigned int i=0; i0) + { + if (GetMemory( Textures[i], tex.Size[i])) return -1; + for (unsigned int j=0u; j. +*/ + + +#ifndef uMod_ADDTEXTURE_H_ +#define uMod_ADDTEXTURE_H_ + +#include "uMod_Main.h" + +class AddTextureClass +{ +public: + AddTextureClass(void); + ~AddTextureClass(void); + int ReleaseMemory(void); + + int SetSize(int num); + int InheriteMemory(AddTextureClass &tex); + + unsigned int Num; + char **Textures; + unsigned int *Size; + unsigned long *Hash; + bool *WasAdded; + unsigned int Len; + + bool Add; + bool Force; + bool Loaded; + bool OwnMemory; + wxString File; + wxString Comment; + + +}; + + + +#endif /* uMod_ADDTEXTURE_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Client.cpp b/uMod2/uMod_GUI/uMod_Client.cpp new file mode 100644 index 0000000..4d99934 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Client.cpp @@ -0,0 +1,93 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + +uMod_Client::uMod_Client( PipeStruct &pipe, uMod_Frame *frame) : wxThread(wxTHREAD_JOINABLE) +{ + Pipe.In = pipe.In; + Pipe.Out = pipe.Out; + MainFrame = frame; +} + +uMod_Client::~uMod_Client(void) +{ + if (Pipe.Out != INVALID_HANDLE_VALUE) + { + DisconnectNamedPipe(Pipe.Out); + CloseHandle(Pipe.Out); + Pipe.Out = INVALID_HANDLE_VALUE; + } + if (Pipe.In != INVALID_HANDLE_VALUE) + { + DisconnectNamedPipe(Pipe.In); + CloseHandle(Pipe.In); + Pipe.In = INVALID_HANDLE_VALUE; + } +} + +void* uMod_Client::Entry(void) +{ + char buffer[SMALL_BUFSIZE]; + while (1) + { + unsigned long size; + bool ret = ReadFile( + Pipe.In, // handle to pipe + buffer, // buffer to receive data + SMALL_BUFSIZE, // size of buffer + &size, // number of bytes read + NULL); // not overlapped I/O + + if (ret || GetLastError()==ERROR_MORE_DATA) + { + unsigned int pos=0; + MsgStruct *commands; + bool update_textures = false; + while (posControl) + { + + } + */ + pos+=sizeof(MsgStruct);// + add_length; + } + } + else + { + break; + } + } + CloseHandle(Pipe.In); + Pipe.In = INVALID_HANDLE_VALUE; + CloseHandle(Pipe.Out); + Pipe.Out = INVALID_HANDLE_VALUE; + + uMod_Event event( uMod_EVENT_TYPE, ID_Delete_Game); + event.SetClient(this); + wxPostEvent( MainFrame, event); + + return NULL; +} + diff --git a/uMod2/uMod_GUI/uMod_Client.h b/uMod2/uMod_GUI/uMod_Client.h new file mode 100644 index 0000000..328b560 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Client.h @@ -0,0 +1,45 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_CLIENT_H_ +#define uMod_CLIENT_H_ + +#include "uMod_Main.h" + +// an object of this class is created for each running game +// it reads out of the incoming pipe (it must run as thread) +// if the pipe is closed (Game is canceled) it send a messeage to the main thread +// it should read the error state from the dll, but this is not yet implemented +class uMod_Client : public wxThread +{ +public: + uMod_Client( PipeStruct &pipe, uMod_Frame *frame); + virtual ~uMod_Client(void); + + void* Entry(void); + + + PipeStruct Pipe; + +private: + uMod_Frame *MainFrame; +}; + +#endif /* uMod_CLIENT_H_ */ diff --git a/uMod2/uMod_GUI/uMod_DirectInjection.cpp b/uMod2/uMod_GUI/uMod_DirectInjection.cpp new file mode 100644 index 0000000..21ed3b0 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_DirectInjection.cpp @@ -0,0 +1,519 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +/* + * + * Drew_Benton + * http://www.codeproject.com/KB/threads/completeinject.aspx + * + */ + +#include "uMod_Main.h" +/***************************************************************************************************/ +// Function: +// Inject +// +// Parameters: +// HANDLE hProcess - The handle to the process to inject the DLL into. +// +// const char* dllname - The name of the DLL to inject into the process. +// +// const char* funcname - The name of the function to call once the DLL has been injected. +// +// Description: +// This function will inject a DLL into a process and execute an exported function +// from the DLL to "initialize" it. The function should be in the format shown below, +// not parameters and no return type. Do not forget to prefix extern "C" if you are in C++ +// +// __declspec(dllexport) void FunctionName(void) +// +// The function that is called in the injected DLL +// -MUST- return, the loader waits for the thread to terminate before removing the +// allocated space and returning control to the Loader. This method of DLL injection +// also adds error handling, so the end user knows if something went wrong. +/***************************************************************************************************/ + +void Inject(HANDLE hProcess, const wchar_t* dllname, const char* funcname) +{ +//------------------------------------------// +// Function variables. // +//------------------------------------------// + + // Main DLL we will need to load + HMODULE kernel32 = NULL; + + // Main functions we will need to import + FARPROC loadlibrary = NULL; + FARPROC getprocaddress = NULL; + FARPROC exitprocess = NULL; + FARPROC exitthread = NULL; + FARPROC freelibraryandexitthread = NULL; + + // The workspace we will build the codecave on locally + LPBYTE workspace = NULL; + DWORD workspaceIndex = 0; + + // The memory in the process we write to + LPVOID codecaveAddress = NULL; + DWORD dwCodecaveAddress = 0; + + // Strings we have to write into the process + char injectDllName[MAX_PATH + 1] = {0}; + char injectFuncName[MAX_PATH + 1] = {0}; + char injectError0[MAX_PATH + 1] = {0}; + char injectError1[MAX_PATH + 1] = {0}; + char injectError2[MAX_PATH + 1] = {0}; + char user32Name[MAX_PATH + 1] = {0}; + char msgboxName[MAX_PATH + 1] = {0}; + + // Placeholder addresses to use the strings + DWORD user32NameAddr = 0; + DWORD user32Addr = 0; + DWORD msgboxNameAddr = 0; + DWORD msgboxAddr = 0; + DWORD dllAddr = 0; + DWORD dllNameAddr = 0; + DWORD funcNameAddr = 0; + DWORD error0Addr = 0; + DWORD error1Addr = 0; + DWORD error2Addr = 0; + + // Where the codecave execution should begin at + DWORD codecaveExecAddr = 0; + + // Handle to the thread we create in the process + HANDLE hThread = NULL; + + // Temp variables + DWORD dwTmpSize = 0; + + // Old protection on page we are writing to in the process and the bytes written + DWORD oldProtect = 0; + DWORD bytesRet = 0; + +//------------------------------------------// +// Variable initialization. // +//------------------------------------------// + + // Get the address of the main DLL + kernel32 = LoadLibraryW(L"kernel32.dll"); + + // Get our functions + loadlibrary = GetProcAddress(kernel32, "LoadLibraryA"); + getprocaddress = GetProcAddress(kernel32, "GetProcAddress"); + exitprocess = GetProcAddress(kernel32, "ExitProcess"); + exitthread = GetProcAddress(kernel32, "ExitThread"); + freelibraryandexitthread = GetProcAddress(kernel32, "FreeLibraryAndExitThread"); + +// This section will cause compiler warnings on VS8, +// you can upgrade the functions or ignore them + + // Build names + _snprintf(injectDllName, MAX_PATH, "%ls", dllname); + _snprintf(injectFuncName, MAX_PATH, "%s", funcname); + _snprintf(user32Name, MAX_PATH, "user32.dll"); + _snprintf(msgboxName, MAX_PATH, "MessageBoxA"); + + // Build error messages + _snprintf(injectError0, MAX_PATH, "Error"); + _snprintf(injectError1, MAX_PATH, "Could not load the dll: %s", injectDllName); + _snprintf(injectError2, MAX_PATH, "Could not load the function: %s", injectFuncName); + + // Create the workspace + workspace = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1024); + + // Allocate space for the codecave in the process + codecaveAddress = VirtualAllocEx(hProcess, 0, 1024, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + dwCodecaveAddress = PtrToUlong(codecaveAddress); + +// Note there is no error checking done above for any functions that return a pointer/handle. +// I could have added them, but it'd just add more messiness to the code and not provide any real +// benefit. It's up to you though in your final code if you want it there or not. + +//------------------------------------------// +// Data and string writing. // +//------------------------------------------// + + // Write out the address for the user32 dll address + user32Addr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = 0; + memcpy(workspace + workspaceIndex, &dwTmpSize, 4); + workspaceIndex += 4; + + // Write out the address for the MessageBoxA address + msgboxAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = 0; + memcpy(workspace + workspaceIndex, &dwTmpSize, 4); + workspaceIndex += 4; + + // Write out the address for the injected DLL's module + dllAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = 0; + memcpy(workspace + workspaceIndex, &dwTmpSize, 4); + workspaceIndex += 4; + + // User32 Dll Name + user32NameAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(user32Name) + 1; + memcpy(workspace + workspaceIndex, user32Name, dwTmpSize); + workspaceIndex += dwTmpSize; + + // MessageBoxA name + msgboxNameAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(msgboxName) + 1; + memcpy(workspace + workspaceIndex, msgboxName, dwTmpSize); + workspaceIndex += dwTmpSize; + + // Dll Name + dllNameAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(injectDllName) + 1; + memcpy(workspace + workspaceIndex, injectDllName, dwTmpSize); + workspaceIndex += dwTmpSize; + + // Function Name + funcNameAddr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(injectFuncName) + 1; + memcpy(workspace + workspaceIndex, injectFuncName, dwTmpSize); + workspaceIndex += dwTmpSize; + + // Error Message 1 + error0Addr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(injectError0) + 1; + memcpy(workspace + workspaceIndex, injectError0, dwTmpSize); + workspaceIndex += dwTmpSize; + + // Error Message 2 + error1Addr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(injectError1) + 1; + memcpy(workspace + workspaceIndex, injectError1, dwTmpSize); + workspaceIndex += dwTmpSize; + + + // Error Message 3 + error2Addr = workspaceIndex + dwCodecaveAddress; + dwTmpSize = (DWORD)strlen(injectError2) + 1; + memcpy(workspace + workspaceIndex, injectError2, dwTmpSize); + workspaceIndex += dwTmpSize; + + // Pad a few INT3s after string data is written for seperation + workspace[workspaceIndex++] = 0xCC; + workspace[workspaceIndex++] = 0xCC; + workspace[workspaceIndex++] = 0xCC; + + // Store where the codecave execution should begin + codecaveExecAddr = workspaceIndex + dwCodecaveAddress; + +// For debugging - infinite loop, attach onto process and step over + //workspace[workspaceIndex++] = 0xEB; + //workspace[workspaceIndex++] = 0xFE; + +//------------------------------------------// +// User32.dll loading. // +//------------------------------------------// + +// User32 DLL Loading + // PUSH 0x00000000 - Push the address of the DLL name to use in LoadLibraryA + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &user32NameAddr, 4); + workspaceIndex += 4; + + // MOV EAX, ADDRESS - Move the address of LoadLibraryA into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &loadlibrary, 4); + workspaceIndex += 4; + + // CALL EAX - Call LoadLibraryA + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + +// MessageBoxA Loading + // PUSH 0x000000 - Push the address of the function name to load + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &msgboxNameAddr, 4); + workspaceIndex += 4; + + // Push EAX, module to use in GetProcAddress + workspace[workspaceIndex++] = 0x50; + + // MOV EAX, ADDRESS - Move the address of GetProcAddress into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &getprocaddress, 4); + workspaceIndex += 4; + + // CALL EAX - Call GetProcAddress + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + + // MOV [ADDRESS], EAX - Save the address to our variable + workspace[workspaceIndex++] = 0xA3; + memcpy(workspace + workspaceIndex, &msgboxAddr, 4); + workspaceIndex += 4; + +//------------------------------------------// +// Injected dll loading. // +//------------------------------------------// + +/* + // This is the way the following assembly code would look like in C/C++ + + // Load the injected DLL into this process + HMODULE h = LoadLibrary("mydll.dll"); + if(!h) + { + MessageBox(0, "Could not load the dll: mydll.dll", "Error", MB_ICONERROR); + ExitProcess(0); + } + + // Get the address of the export function + FARPROC p = GetProcAddress(h, "Initialize"); + if(!p) + { + MessageBox(0, "Could not load the function: Initialize", "Error", MB_ICONERROR); + ExitProcess(0); + } + + // So we do not need a function pointer interface + __asm call p + + // Exit the thread so the loader continues + ExitThread(0); +*/ + +// DLL Loading + // PUSH 0x00000000 - Push the address of the DLL name to use in LoadLibraryA + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &dllNameAddr, 4); + workspaceIndex += 4; + + // MOV EAX, ADDRESS - Move the address of LoadLibraryA into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &loadlibrary, 4); + workspaceIndex += 4; + + // CALL EAX - Call LoadLibraryA + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + +// Error Checking + // CMP EAX, 0 + workspace[workspaceIndex++] = 0x83; + workspace[workspaceIndex++] = 0xF8; + workspace[workspaceIndex++] = 0x00; + +// JNZ EIP + 0x1E to skip over eror code + workspace[workspaceIndex++] = 0x75; + workspace[workspaceIndex++] = 0x1E; + +// Error Code 1 + // MessageBox + // PUSH 0x10 (MB_ICONHAND) + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x10; + + // PUSH 0x000000 - Push the address of the MessageBox title + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &error0Addr, 4); + workspaceIndex += 4; + + // PUSH 0x000000 - Push the address of the MessageBox message + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &error1Addr, 4); + workspaceIndex += 4; + + // Push 0 + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // MOV EAX, [ADDRESS] - Move the address of MessageBoxA into EAX + workspace[workspaceIndex++] = 0xA1; + memcpy(workspace + workspaceIndex, &msgboxAddr, 4); + workspaceIndex += 4; + + // CALL EAX - Call MessageBoxA + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + + // ExitProcess + // Push 0 + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // MOV EAX, ADDRESS - Move the address of ExitProcess into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &exitprocess, 4); + workspaceIndex += 4; + + // CALL EAX - Call MessageBoxA + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + +// Now we have the address of the injected DLL, so save the handle + + // MOV [ADDRESS], EAX - Save the address to our variable + workspace[workspaceIndex++] = 0xA3; + memcpy(workspace + workspaceIndex, &dllAddr, 4); + workspaceIndex += 4; + +// Load the initilize function from it + + // PUSH 0x000000 - Push the address of the function name to load + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &funcNameAddr, 4); + workspaceIndex += 4; + + // Push EAX, module to use in GetProcAddress + workspace[workspaceIndex++] = 0x50; + + // MOV EAX, ADDRESS - Move the address of GetProcAddress into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &getprocaddress, 4); + workspaceIndex += 4; + + // CALL EAX - Call GetProcAddress + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + +// Error Checking + // CMP EAX, 0 + workspace[workspaceIndex++] = 0x83; + workspace[workspaceIndex++] = 0xF8; + workspace[workspaceIndex++] = 0x00; + +// JNZ EIP + 0x1C to skip eror code + workspace[workspaceIndex++] = 0x75; + workspace[workspaceIndex++] = 0x1C; + +// Error Code 2 + // MessageBox + // PUSH 0x10 (MB_ICONHAND) + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x10; + + // PUSH 0x000000 - Push the address of the MessageBox title + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &error0Addr, 4); + workspaceIndex += 4; + + // PUSH 0x000000 - Push the address of the MessageBox message + workspace[workspaceIndex++] = 0x68; + memcpy(workspace + workspaceIndex, &error2Addr, 4); + workspaceIndex += 4; + + // Push 0 + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // MOV EAX, ADDRESS - Move the address of MessageBoxA into EAX + workspace[workspaceIndex++] = 0xA1; + memcpy(workspace + workspaceIndex, &msgboxAddr, 4); + workspaceIndex += 4; + + // CALL EAX - Call MessageBoxA + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + + // ExitProcess + // Push 0 + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // MOV EAX, ADDRESS - Move the address of ExitProcess into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &exitprocess, 4); + workspaceIndex += 4; + +// Now that we have the address of the function, we cam call it, +// if there was an error, the messagebox would be called as well. + + // CALL EAX - Call ExitProcess -or- the Initialize function + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; + + // If we get here, the Initialize function has been called, + // so it's time to close this thread and optionally unload the DLL. + +//------------------------------------------// +// Exiting from the injected dll. // +//------------------------------------------// + +// Call ExitThread to leave the DLL loaded +#if 1 + // Push 0 (exit code) + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // MOV EAX, ADDRESS - Move the address of ExitThread into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &exitthread, 4); + workspaceIndex += 4; + + // CALL EAX - Call ExitThread + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; +#endif + +// Call FreeLibraryAndExitThread to unload DLL +#if 0 + // Push 0 (exit code) + workspace[workspaceIndex++] = 0x6A; + workspace[workspaceIndex++] = 0x00; + + // PUSH [0x000000] - Push the address of the DLL module to unload + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0x35; + memcpy(workspace + workspaceIndex, &dllAddr, 4); + workspaceIndex += 4; + + // MOV EAX, ADDRESS - Move the address of FreeLibraryAndExitThread into EAX + workspace[workspaceIndex++] = 0xB8; + memcpy(workspace + workspaceIndex, &freelibraryandexitthread, 4); + workspaceIndex += 4; + + // CALL EAX - Call FreeLibraryAndExitThread + workspace[workspaceIndex++] = 0xFF; + workspace[workspaceIndex++] = 0xD0; +#endif + +//------------------------------------------// +// Code injection and cleanup. // +//------------------------------------------// + + // Change page protection so we can write executable code + VirtualProtectEx(hProcess, codecaveAddress, workspaceIndex, PAGE_EXECUTE_READWRITE, &oldProtect); + + // Write out the patch + WriteProcessMemory(hProcess, codecaveAddress, workspace, workspaceIndex, &bytesRet); + + // Restore page protection + VirtualProtectEx(hProcess, codecaveAddress, workspaceIndex, oldProtect, &oldProtect); + + // Make sure our changes are written right away + FlushInstructionCache(hProcess, codecaveAddress, workspaceIndex); + + // Free the workspace memory + HeapFree(GetProcessHeap(), 0, workspace); + + // Execute the thread now and wait for it to exit, note we execute where the code starts, and not the codecave start + // (since we wrote strings at the start of the codecave) -- NOTE: void* used for VC6 compatibility instead of UlongToPtr + hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)((void*)codecaveExecAddr), 0, 0, NULL); + WaitForSingleObject(hThread, INFINITE); + + // Free the memory in the process that we allocated + VirtualFreeEx(hProcess, codecaveAddress, 0, MEM_RELEASE); +} diff --git a/uMod2/uMod_GUI/uMod_DirectInjection.h b/uMod2/uMod_GUI/uMod_DirectInjection.h new file mode 100644 index 0000000..d491a3c --- /dev/null +++ b/uMod2/uMod_GUI/uMod_DirectInjection.h @@ -0,0 +1,27 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + +#ifndef uMod_INJECTDIRECTLY_H_ +#define uMod_INJECTDIRECTLY_H_ + + + +void Inject(HANDLE hProcess, const wchar_t* dllname, const char* funcname); + +#endif /* uMod_INJECTDIRECTLY_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Event.cpp b/uMod2/uMod_GUI/uMod_Event.cpp new file mode 100644 index 0000000..bffc0ca --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Event.cpp @@ -0,0 +1,23 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + diff --git a/uMod2/uMod_GUI/uMod_Event.h b/uMod2/uMod_GUI/uMod_Event.h new file mode 100644 index 0000000..5c09fe9 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Event.h @@ -0,0 +1,70 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_EVENTTYPE_H_ +#define uMod_EVENTTYPE_H_ +#include "uMod_Client.h" +#include "uMod_Main.h" + + +//we need our own event to pass send some arguments from the server or the client thread to the main thread +BEGIN_DECLARE_EVENT_TYPES() +DECLARE_EVENT_TYPE( uMod_EVENT_TYPE, -1) +END_DECLARE_EVENT_TYPES() + +class uMod_Event : public wxCommandEvent +{ +public: + uMod_Event( wxEventType commandType = uMod_EVENT_TYPE, int id = 0 ) + : wxCommandEvent(commandType, id) { } + virtual ~uMod_Event(void) {} + + // You *must* copy here the data to be transported + uMod_Event( const uMod_Event &event ) + : wxCommandEvent(event) { this->SetText( event.GetText()); PipeIn=((uMod_Event&)event).GetPipeIn(); PipeOut=((uMod_Event&)event).GetPipeOut(); Name=((uMod_Event&)event).GetName(); Client=((uMod_Event&)event).GetClient();} + + // Required for sending with wxPostEvent() + wxEvent* Clone() const { return new uMod_Event(*this); } + + wxString GetText() const { return m_Text; } + void SetText( const wxString& text ) { m_Text = text; } + + wxString GetName(void) {return Name;} + HANDLE GetPipeIn(void) {return PipeIn;} + HANDLE GetPipeOut(void) {return PipeOut;} + uMod_Client * GetClient(void) {return Client;} + + void SetName( wxString name) {Name=name;} + void SetPipeIn( HANDLE pipe) {PipeIn=pipe;} + void SetPipeOut( HANDLE pipe) {PipeOut=pipe;} + void SetClient( uMod_Client *client) {Client=client;} + +private: + + wxString Name; + HANDLE PipeIn; + HANDLE PipeOut; + uMod_Client *Client; + + wxString m_Text; +}; + + +#endif /* uMod_EVENTTYPE_H_ */ diff --git a/uMod2/uMod_GUI/uMod_File.cpp b/uMod2/uMod_GUI/uMod_File.cpp new file mode 100644 index 0000000..ff4ab77 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_File.cpp @@ -0,0 +1,441 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +#include "uMod_Main.h" +#include "unzip.h" + + +uMod_File::uMod_File(void) +{ + Loaded=false; + XORed=false; + FileInMemory=NULL; + MemoryLength=0u; + FileLen=0u; +} + +uMod_File::uMod_File(const wxString &file) +{ + Loaded=false; + XORed=false; + FileInMemory=NULL; + MemoryLength=0u; + FileLen=0u; + SetFile(file); +} + + +uMod_File::~uMod_File(void) +{ + if (FileInMemory!=NULL) delete [] FileInMemory; +} + + +bool uMod_File::FileSupported(void) +{ + wxString file_type = FileName.AfterLast( '.'); + if (file_type == L"zip") return true; + else if (file_type == L"tpf") return true; + else if (file_type == L"dds") return true; + + return false; +} + + +int uMod_File::GetComment( wxString &tool_tip) +{ + wxString file_type = FileName.AfterLast( '.'); + if (file_type == L"zip") + { + if (int ret = GetCommentZip( tool_tip)) return ret; + } + else if (file_type == L"tpf") + { + if (int ret = GetCommentTpf( tool_tip)) return ret; + } + else if (file_type == L"dds") + { + tool_tip = Language->NoComment; + return -1; + } + return 0; +} + +int uMod_File::GetContent( AddTextureClass &tex, bool add) +{ + wxString file_type = FileName.AfterLast( '.'); + if (file_type == L"zip") + { + AddZip( tex, add, false); + } + else if (file_type == L"tpf") + { + AddZip( tex, add, true); + } + else if (file_type == L"dds") + { + AddFile( tex, add); + } + else + { + LastError << Language->Error_FileNotSupported; + LastError << "\n" << FileName; + } + if (LastError.Len()>0) return -1; + else + { + if (add) tex.Loaded = true; + return 0; + } +} + +int uMod_File::ReadFile(void) +{ + if (Loaded) return 0; + XORed=false; + + wxFile dat; + if (!dat.Access(FileName, wxFile::read)) {LastError << Language->Error_FileOpen <<"\n" << FileName; return -1;} + dat.Open(FileName, wxFile::read); + if (!dat.IsOpened()) {LastError << Language->Error_FileOpen <<"\n" << FileName; return -1;} + FileLen = dat.Length(); + if (FileLen==0) {LastError << Language->Error_FileOpen <<"\n" << FileName; return -1;} + + if (FileLen>=MemoryLength) + { + if (FileInMemory!=NULL) delete [] FileInMemory; + try {FileInMemory = new char [FileLen+1];} + catch (...) {FileInMemory=NULL; MemoryLength=0; FileLen=0; LastError << Language->Error_Memory; return -1;} + MemoryLength = FileLen+1; + } + unsigned int result = dat.Read( FileInMemory, FileLen); + dat.Close(); + + if (result != FileLen) {FileLen=0; LastError << Language->Error_FileRead<<"\n" << FileName; return -1;} + FileInMemory[FileLen]=0; + + Loaded = true; + return 0; +} + + + +int uMod_File::UnXOR(void) +{ + if (XORed) return 0; + /* + * + * BIG THANKS TO Tonttu + * (TPFcreate 1.5) + * + */ + unsigned int *buff = (unsigned int*) FileInMemory; + unsigned int TPF_XOR = 0x3FA43FA4u; + unsigned int size = FileLen/4u; + for (unsigned int i=0; i0u && FileInMemory[pos]) pos--; + if (pos>0u && pos> 24 ); + TPF_XOR <<= 4; + j++; + } + */ + return 0; +} + + + +int uMod_File::GetCommentZip( wxString &tool_tip) +{ + if (int ret = ReadFile()) return ret; + + HZIP ZIP_Handle = OpenZip( FileInMemory, FileLen, NULL); + if (ZIP_Handle==NULL) {tool_tip = Language->NoComment; LastError << Language->Error_Unzip; return -1;} + + ZIPENTRY ze; + int index; + FindZipItem( ZIP_Handle, L"Comment.txt", false, &index, &ze); + if (index>=0) //if Comment.txt is present in the zip file + { + char* comment; + int len = ze.unc_size; + try {comment=new char[len+1];} + catch(...) {tool_tip = Language->NoComment; LastError << Language->Error_Memory; return -1;} + ZRESULT zr = UnzipItem( ZIP_Handle, index, comment, len); + + if (zr!=ZR_OK && zr!=ZR_MORE) {delete [] comment; tool_tip = Language->NoComment; LastError << Language->Error_Unzip <<"\nZIP:" << L"Comment.txt"; return -1;} + comment[len]=0; + tool_tip = comment; + delete [] comment; + } + else tool_tip = Language->NoComment; + + CloseZip(ZIP_Handle); + return 0; +} + +int uMod_File::GetCommentTpf( wxString &tool_tip) +{ + if (int ret = ReadFile()) return ret; + + UnXOR(); + tool_tip = &FileInMemory[FileLen]; + tool_tip.Prepend( Language->Author); + return 0; +} + + + + + + + + + +int uMod_File::AddFile( AddTextureClass &tex, bool add) +{ + tex.SetSize(1); + unsigned long temp_hash; + + wxString name = FileName.AfterLast( '_'); + name = name.BeforeLast( '.'); + if (!name.ToULong( &temp_hash, 16)) {LastError << Language->Error_Hash <<"\n" << FileName << "\n"; return -1;} // return if hash could not be extracted + + if (add) + { + if (int ret = ReadFile()) return ret; + + try {tex.Textures[0] = new char[FileLen];} + catch (...) {tex.Textures[0]=NULL; LastError << Language->Error_Memory; return -1;} + for (unsigned int i=0; iError_Unzip; return -1;} + + ZIPENTRY ze; + int index; + FindZipItem( ZIP_Handle, L"texmod.def", false, &index, &ze); + if (index>=0) //if texmod.def is present in the zip file + { + char* def; + int len = ze.unc_size; + try {def=new char[len+1];} + catch(...) {LastError << Language->Error_Memory; return -1;} + ZRESULT zr = UnzipItem( ZIP_Handle, index, def, len); + + if (zr!=ZR_OK && zr!=ZR_MORE) {delete [] def; return -1;} + def[len]=0; + + wxStringTokenizer token( def, "\n"); + + int num = token.CountTokens(); + + + tex.SetSize(num); + + unsigned long temp_hash; + int count = 0; + wxString entry; + wxString file; + + for (int i=0; iError_Hash <<"\nTPF:" << entry << "\n"; continue;} + + file = entry.AfterFirst( '|'); + file.Replace( "\r", ""); + + while ( (file[0]=='.' && (file[1]=='/' || file[1]=='\\')) || file[0]=='/' || file[0]=='\\') file.Remove(0,1); + + if (add) + { + FindZipItem( ZIP_Handle, file.wc_str(), false, &index, &ze); // look for texture + if (index>=0) + { + try {tex.Textures[count] = new char[ze.unc_size];} + catch(...) + { + tex.Textures[count] = NULL; + LastError << Language->Error_Memory; + continue; + } + + ZRESULT rz = UnzipItem( ZIP_Handle, index, tex.Textures[count], ze.unc_size); + if (rz!=ZR_OK && rz!=ZR_MORE) + { + delete [] tex.Textures[count]; + LastError << Language->Error_Unzip <<"\nTPF:" << file << "\n"; + tex.Textures[count] = NULL; + } + else + { + tex.Hash[count] = temp_hash; + tex.Size[count] = ze.unc_size; + count++; + } + } + else + { + LastError << Language->Error_Unzip <<"\nTPF:" << file << "\n"; + CloseZip(ZIP_Handle); //somehow we need to close and to reopen the zip handle, otherwise the program crashes + ZIP_Handle = OpenZip( FileInMemory, FileLen, pw); + } + } + else + { + tex.Hash[count] = temp_hash; + tex.Size[count] = 0; + count++; + } + } + delete [] def; + tex.Num = count; + } + else // texmod.def is not present in the zip file + { + CloseZip(ZIP_Handle); //somehow we need to close and to reopen the zip handle, otherwise the program crashes + ZIP_Handle = OpenZip( FileInMemory, FileLen, pw); + if (ZIP_Handle==NULL) {LastError << Language->Error_Unzip; return -1;} + wxString name; + wxString file; + GetZipItem( ZIP_Handle, -1, &ze); //ask for number of entries + int num = ze.index; + + tex.SetSize(num); + int count = 0; + unsigned long temp_hash; + for (int i=0; iError_Unzip <<"\nZIP:" << file << "\n"; + } + + file = ze.name; + if (file.Len()==0) continue; + + name = file.AfterLast( '.'); + if (name!="dds") continue; //if this is not texture file, continue + + name = file.AfterLast( '_'); + name = name.BeforeLast( '.'); + + if (!name.ToULong( &temp_hash, 16)) {LastError << Language->Error_Hash <<"\nZIP:" << file << "\n"; continue;} //if hash could not be extracted + + if (add) + { + if (buffer==NULL) continue; + + tex.Textures[count] = buffer; + tex.Hash[count] = temp_hash; + tex.Size[count] = len;//ze.unc_size; + count++; + } + else + { + if (buffer!=NULL) delete [] buffer; + tex.Hash[count] = temp_hash; + tex.Size[count] = 0; + count++; + } + } + tex.Num = count; + } + + CloseZip(ZIP_Handle); + return 0; +} diff --git a/uMod2/uMod_GUI/uMod_File.h b/uMod2/uMod_GUI/uMod_File.h new file mode 100644 index 0000000..f2e4ac2 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_File.h @@ -0,0 +1,62 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +#ifndef uMod_FILE_H_ +#define uMod_FILE_H_ + +#include "uMod_Main.h" + +class uMod_File +{ +public: + uMod_File(void); + uMod_File(const wxString &file); + ~uMod_File(void); + + bool FileSupported(void); + + int GetComment( wxString &tool_tip); + int GetContent( AddTextureClass &tex, bool add); + + int SetFile(const wxString &file) {FileName=file;Loaded=false; return 0;} + wxString GetFile(void) {return FileName;} + + + wxString LastError; + +private: + int ReadFile(void); + + int UnXOR(void); + int GetCommentZip( wxString &tool_tip); + int GetCommentTpf( wxString &tool_tip); + + int AddFile( AddTextureClass &tex, bool add); + int AddZip( AddTextureClass &tex, bool add, bool tpf); + int AddContent( const char* pw, AddTextureClass &tex, bool add); + + wxString FileName; + bool Loaded; + bool XORed; + char *FileInMemory; + unsigned int MemoryLength; + unsigned int FileLen; +}; + + +#endif /* uMod_FILE_H_ */ diff --git a/uMod2/uMod_GUI/uMod_GUI.cpp b/uMod2/uMod_GUI/uMod_GUI.cpp new file mode 100644 index 0000000..2023593 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_GUI.cpp @@ -0,0 +1,985 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + + + +#include "uMod_Main.h" + + + + + +#ifndef __CDT_PARSER__ + +DEFINE_EVENT_TYPE(uMod_EVENT_TYPE) + +BEGIN_EVENT_TABLE(uMod_Frame, wxFrame) + EVT_CLOSE(uMod_Frame::OnClose) + + EVT_BUTTON(ID_Button_Open, uMod_Frame::OnButtonOpen) + EVT_BUTTON(ID_Button_Path, uMod_Frame::OnButtonPath) + EVT_BUTTON(ID_Button_Update, uMod_Frame::OnButtonUpdate) + EVT_BUTTON(ID_Button_Reload, uMod_Frame::OnButtonReload) + + EVT_MENU(ID_Menu_Help, uMod_Frame::OnMenuHelp) + EVT_MENU(ID_Menu_About, uMod_Frame::OnMenuAbout) + EVT_MENU(ID_Menu_Acknowledgement, uMod_Frame::OnMenuAcknowledgement) + + + EVT_MENU(ID_Menu_StartGame, uMod_Frame::OnMenuStartGame) + EVT_MENU(ID_Menu_StartGameCMD, uMod_Frame::OnMenuStartGame) + + EVT_MENU(ID_Menu_AddGame, uMod_Frame::OnMenuAddGame) + EVT_MENU(ID_Menu_DeleteGame, uMod_Frame::OnMenuDeleteGame) + EVT_MENU(ID_Menu_UseHook, uMod_Frame::OnMenuUseHook) + + EVT_MENU(ID_Menu_LoadTemplate, uMod_Frame::OnMenuOpenTemplate) + EVT_MENU(ID_Menu_SaveTemplate, uMod_Frame::OnMenuSaveTemplate) + EVT_MENU(ID_Menu_SaveTemplateAs, uMod_Frame::OnMenuSaveTemplateAs) + EVT_MENU(ID_Menu_SetDefaultTemplate, uMod_Frame::OnMenuSetDefaultTemplate) + + EVT_MENU(ID_Menu_Lang, uMod_Frame::OnMenuLanguage) + EVT_MENU(ID_Menu_Exit, uMod_Frame::OnMenuExit) + + EVT_COMMAND (ID_Add_Game, uMod_EVENT_TYPE, uMod_Frame::OnAddGame) + EVT_COMMAND (ID_Delete_Game, uMod_EVENT_TYPE, uMod_Frame::OnDeleteGame) +END_EVENT_TABLE() + +IMPLEMENT_APP(MyApp) +#endif + +MyApp::~MyApp(void) +{ + if (CheckForSingleRun!=NULL) CloseHandle( CheckForSingleRun); +} + + +bool MyApp::OnInit(void) +{ + uMod_Settings set; + set.Load(); + + Language = new uMod_Language(set.Language); + CheckForSingleRun = CreateMutex( NULL, true, L"Global\\uMod_CheckForSingleRun"); + if (ERROR_ALREADY_EXISTS == GetLastError()) + { + wxMessageBox( Language->Error_AlreadyRunning, "ERROR", wxOK|wxICON_ERROR); + return false; + } + uMod_Frame *frame = new uMod_Frame( uMod_VERSION, set); + SetTopWindow( frame ); + + return true; +} + + +uMod_Frame::uMod_Frame(const wxString& title, uMod_Settings &set) + : wxFrame((wxFrame *)NULL, -1, title, wxPoint(set.XPos,set.YPos), wxSize(set.XSize,set.YSize)), Settings(set) +{ + SetIcon(wxICON(MAINICON)); + H_DX9_DLL = NULL; + + Server = new uMod_Server( this); + Server->Create(); + Server->Run(); + + MenuBar = new wxMenuBar; + //MenuMain = new wxMenu; + MenuMain = new wxMenu; + MenuHelp = new wxMenu; + + MenuMain->Append ( ID_Menu_StartGame, Language->MenuStartGame); + MenuMain->Append ( ID_Menu_StartGameCMD, Language->MenuStartGameCMD); + MenuMain->AppendSeparator(); + + MenuMain->Append( ID_Menu_AddGame, Language->MenuAddGame ); + MenuMain->Append( ID_Menu_DeleteGame, Language->MenuDeleteGame ); + MenuMain->AppendCheckItem ( ID_Menu_UseHook, Language->MenuUseHook); + MenuMain->Check( ID_Menu_UseHook, Settings.UseHook); + + MenuMain->AppendSeparator(); + MenuMain->Append( ID_Menu_LoadTemplate, Language->MenuLoadTemplate ); + MenuMain->Append( ID_Menu_SaveTemplate, Language->MenuSaveTemplate ); + MenuMain->Append( ID_Menu_SaveTemplateAs, Language->MenuSaveTemplateAs ); + MenuMain->Append( ID_Menu_SetDefaultTemplate, Language->MenuSetDefaultTemplate ); + MenuMain->AppendSeparator(); + MenuMain->Append( ID_Menu_Lang, Language->MenuLanguage ); + MenuMain->Append( ID_Menu_Exit, Language->MenuExit ); + + MenuHelp->Append( ID_Menu_Help, Language->MenuHelp ); + MenuHelp->Append( ID_Menu_About, Language->MenuAbout ); + MenuHelp->Append( ID_Menu_Acknowledgement, Language->MenuAcknowledgement ); + + MenuBar->Append( MenuMain, Language->MainMenuMain ); + MenuBar->Append( MenuHelp, Language->MainMenuHelp ); + + SetMenuBar(MenuBar); + + + MainSizer = new wxBoxSizer(wxVERTICAL); + + Notebook = new wxNotebook( this, wxID_ANY); + Notebook->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_MENU)); + MainSizer->Add( (wxWindow*) Notebook, 1, wxEXPAND , 0 ); + + ButtonSizer = new wxBoxSizer(wxHORIZONTAL); + + OpenButton = new wxButton( this, ID_Button_Open, Language->ButtonOpen, wxDefaultPosition, wxSize(100,24)); + DirectoryButton = new wxButton( this, ID_Button_Path, Language->ButtonDirectory, wxDefaultPosition, wxSize(100,24)); + UpdateButton = new wxButton( this, ID_Button_Update, Language->ButtonUpdate, wxDefaultPosition, wxSize(100,24)); + ReloadButton = new wxButton( this, ID_Button_Reload, Language->ButtonReload, wxDefaultPosition, wxSize(100,24)); + + ButtonSizer->Add( (wxWindow*) OpenButton, 1, wxEXPAND, 0); + ButtonSizer->Add( (wxWindow*) DirectoryButton, 1, wxEXPAND, 0); + ButtonSizer->Add( (wxWindow*) UpdateButton, 1, wxEXPAND, 0); + ButtonSizer->Add( (wxWindow*) ReloadButton, 1, wxEXPAND, 0); + MainSizer->Add( ButtonSizer, 0, wxEXPAND , 0 ); + + + SetSizer( MainSizer); + + NumberOfGames = 0; + MaxNumberOfGames = 10; + Clients = NULL; + if (GetMemory( Clients, MaxNumberOfGames)) + { + wxMessageBox( Language->Error_Memory, "ERROR", wxOK|wxICON_ERROR); + } + LoadTemplate(); + + Show( true ); + + { + HMODULE dll = LoadLibraryW( L"D3DX9_43.dll"); + if (dll==NULL) + { + wxMessageBox( Language->Error_D3DX9NotFound, "ERROR", wxOK|wxICON_ERROR); + } + else FreeLibrary(dll); + } + + if (Settings.UseHook) InstallHook(); + DeactivateGamesControl(); +} + +uMod_Frame::~uMod_Frame(void) +{ + if (Server!=(uMod_Server*)0) + { + KillServer(); + Server->Wait(); + delete Server; + Server = NULL; + } + + RemoveHook(); + + if (Clients!=NULL) delete [] Clients; + + Settings.Language = Language->GetCurrentLanguage(); + GetSize( &Settings.XSize, &Settings.YSize); + GetPosition( &Settings.XPos, &Settings.YPos); + Settings.Save(); +} + +int uMod_Frame::KillServer(void) +{ + HANDLE pipe = CreateFileW( PIPE_Game2uMod,// pipe name + GENERIC_WRITE, + 0, // no sharing + NULL, // default security attributes + OPEN_EXISTING, // opens existing pipe + 0, // default attributes + NULL); // no template file + + if (pipe == INVALID_HANDLE_VALUE) return -1; + + const wchar_t *str = ABORT_SERVER; + unsigned int len=0u; + while (str[len]) len++; + len++; //to send also the zero + unsigned long num; + WriteFile( pipe, (const void*) str, len*sizeof(wchar_t), &num, NULL); + CloseHandle(pipe); + return 0; +} + + + +void uMod_Frame::OnAddGame( wxCommandEvent &event) +{ + if (NumberOfGames>=MaxNumberOfGames) + { + if (GetMoreMemory( Clients, MaxNumberOfGames, MaxNumberOfGames+10)) + { + wxMessageBox( Language->Error_Memory, "ERROR", wxOK|wxICON_ERROR); + return; + } + MaxNumberOfGames += 10; + } + + wxString name = ((uMod_Event&)event).GetName(); + PipeStruct pipe; + + pipe.In = ((uMod_Event&)event).GetPipeIn(); + pipe.Out = ((uMod_Event&)event).GetPipeOut(); + + uMod_Client *client = new uMod_Client( pipe, this); + client->Create(); + client->Run(); + + wxString save_file; + int num = SaveFile_Exe.GetCount(); + for (int i=0; iPipe); + if (page->LastError.Len()>0) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + delete page; + return; + } + name = name.AfterLast('\\'); + name = name.AfterLast('/'); + name = name.BeforeLast('.'); + Notebook->AddPage( page, name, true); + + Clients[NumberOfGames] = client; + NumberOfGames++; + if (NumberOfGames==1) ActivateGamesControl(); +} + +void uMod_Frame::OnDeleteGame( wxCommandEvent &event) +{ + uMod_Client *client = ((uMod_Event&)event).GetClient(); + for (int i=0; iDeletePage(i); + Clients[i]->Wait(); + delete Clients[i]; + NumberOfGames--; + for (int j=i; j0) + { + if (wxMessageBox(Language->ExitGameAnyway, "ERROR", wxYES_NO|wxICON_ERROR)!=wxYES) {event.Veto(); return;} + } + event.Skip(); + Destroy(); +} + +void uMod_Frame::OnButtonOpen(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + + //wxString file_name = wxFileSelector( Language->ChooseFile, page->GetOpenPath(), "", "*.*", "textures (*.dds)|*.dds|zip (*.zip)|*.zip|tpf (*.tpf)|*.tpf", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + wxString file_name = wxFileSelector( Language->ChooseFile, page->GetOpenPath(), "", "", "", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + if ( !file_name.empty() ) + { + page->SetOpenPath(file_name.BeforeLast( '/')); + if (page->AddTexture( file_name)) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } + } +} + +void uMod_Frame::OnButtonPath(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + wxString dir = wxDirSelector( Language->ChooseDir, page->GetSavePath()); + if ( !dir.empty() ) + { + page->SetSavePath( dir); + } +} + +void uMod_Frame::OnButtonUpdate(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + if (page->UpdateGame()) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } +} + +void uMod_Frame::OnButtonReload(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + if (page->ReloadGame()) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } +} + + + + +void uMod_Frame::OnMenuOpenTemplate(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + + //wxString file_name = wxFileSelector( Language->ChooseFile, page->GetOpenPath(), "", "*.*", "textures (*.dds)|*.dds|zip (*.zip)|*.zip|tpf (*.tpf)|*.tpf", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + + wxString dir = wxGetCwd(); + dir << "/templates"; + wxString file_name = wxFileSelector( Language->ChooseFile, dir, "", "*.txt", "text (*.txt)|*.txt", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + if ( !file_name.empty() ) + { + if (page->LoadTemplate( file_name)) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } + } +} + +void uMod_Frame::OnMenuSaveTemplate(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + wxString file_name = page->GetTemplateName(); + + if ( file_name.empty() ) + { + wxString dir = wxGetCwd(); + dir << "/templates"; + file_name = wxFileSelector( Language->ChooseFile, dir, "", "*.txt", "text (*.txt)|*.txt", wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this); + } + if ( !file_name.empty() ) + { + if (page->SaveTemplate(file_name)) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } + } +} + +void uMod_Frame::OnMenuSaveTemplateAs(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + + wxString dir = wxGetCwd(); + dir << "/templates"; + wxString file_name = wxFileSelector( Language->ChooseFile, dir, "", "*.txt", "text (*.txt)|*.txt", wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this); + if ( !file_name.empty() ) + { + if (page->SaveTemplate(file_name)) + { + wxMessageBox(page->LastError, "ERROR", wxOK|wxICON_ERROR); + page->LastError.Empty(); + } + } +} + +void uMod_Frame::OnMenuSetDefaultTemplate(wxCommandEvent& WXUNUSED(event)) +{ + if (Notebook->GetPageCount()==0) return; + uMod_GamePage *page = (uMod_GamePage*) Notebook->GetCurrentPage(); + if (page==NULL) return; + + wxString exe = page->GetExeName(); + wxString file = page->GetTemplateName(); + + int num = SaveFile_Exe.GetCount(); + bool hit = false; + for (int i=0; iGetLanguages( lang); + wxString choice = wxGetSingleChoice( Language->SelectLanguage, Language->SelectLanguage, lang); + if (choice.Len()>0) + { + if (Language->LoadLanguage(choice)) + { + wxMessageBox(Language->LastError, "ERROR", wxOK|wxICON_ERROR); + Language->LastError.Empty(); + return; + } + MenuBar->SetMenuLabel( 0, Language->MainMenuMain); + MenuMain->SetLabel( ID_Menu_StartGame, Language->MenuStartGame); + MenuMain->SetLabel( ID_Menu_StartGameCMD, Language->MenuStartGameCMD); + + MenuMain->SetLabel( ID_Menu_AddGame, Language->MenuAddGame); + MenuMain->SetLabel( ID_Menu_DeleteGame, Language->MenuDeleteGame); + MenuMain->SetLabel( ID_Menu_UseHook, Language->MenuUseHook); + + MenuMain->SetLabel( ID_Menu_LoadTemplate, Language->MenuLoadTemplate ); + MenuMain->SetLabel( ID_Menu_SaveTemplate, Language->MenuSaveTemplate ); + MenuMain->SetLabel( ID_Menu_SaveTemplateAs, Language->MenuSaveTemplateAs ); + MenuMain->SetLabel( ID_Menu_SetDefaultTemplate, Language->MenuSetDefaultTemplate ); + + MenuMain->SetLabel( ID_Menu_Lang, Language->MenuLanguage); + MenuMain->SetLabel( ID_Menu_Exit, Language->MenuExit ); + + MenuBar->SetMenuLabel( 1, Language->MainMenuHelp); + MenuHelp->SetLabel( ID_Menu_Help, Language->MenuHelp); + MenuHelp->SetLabel( ID_Menu_About, Language->MenuAbout); + MenuHelp->SetLabel( ID_Menu_Acknowledgement, Language->MenuAcknowledgement); + + + OpenButton->SetLabel( Language->ButtonOpen); + DirectoryButton->SetLabel( Language->ButtonDirectory); + UpdateButton->SetLabel( Language->ButtonUpdate); + ReloadButton->SetLabel( Language->ButtonReload); + + int num = Notebook->GetPageCount(); + for (int i=0; iGetPage(i); + page->UpdateLanguage(); + } + } +} + +void uMod_Frame::OnMenuExit(wxCommandEvent& WXUNUSED(event)) +{ + Close(); +} + +void uMod_Frame::OnMenuHelp(wxCommandEvent& WXUNUSED(event)) +{ + wxString help; + if (Language->GetHelpMessage( help)) + { + wxMessageBox(Language->LastError, "ERROR", wxOK|wxICON_ERROR); + Language->LastError.Empty(); + return; + } + + wxMessageBox( help, Language->MenuHelp, wxOK); +} + +void uMod_Frame::OnMenuAbout(wxCommandEvent& WXUNUSED(event)) +{ + wxString msg; + msg << uMod_VERSION << "\n\nProject members:\n\nROTA (developer)\nKing Brace Blane (PR)\n\nhttp://code.google.com/p/texmod/"; + wxMessageBox( msg, "Info", wxOK); +} + +void uMod_Frame::OnMenuAcknowledgement(wxCommandEvent& WXUNUSED(event)) +{ + wxString msg; + msg << "King Brace Blane and ROTA thank:\n\n"; + msg << "RS for coding the original TexMod and for information about the used hashing algorithm\n\n"; + msg << "EvilAlex for translation into Russian and bug fixing\n"; + msg << "ReRRemi for translation into French"; + //msg << "King Brace Blane for a tutorial video on YouTube and bug fixing"; + wxMessageBox( msg, Language->MenuAcknowledgement, wxOK); +} + +void uMod_Frame::OnMenuStartGame(wxCommandEvent& event) +{ + bool use_cmd = false; + if (event.GetId() == ID_Menu_StartGameCMD) use_cmd = true; + + wxArrayString games, cmd, choices; + + GetInjectedGames( games, cmd); + int num = games.GetCount(); + + choices = games; + choices.Add( Language->StartGame); + + int index = wxGetSingleChoiceIndex( Language->MenuStartGame, Language->MenuStartGame, choices); + + if (index < 0) return; + else if (index==num) + { + wxString file_name = wxFileSelector( Language->ChooseGame, "", "", "exe", "binary (*.exe)|*.exe", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + if ( !file_name.empty() ) + { + bool hit = false; + for (int i=0; iCommandLine, Language->CommandLine, command_line); + if (!command_line.IsEmpty()) cmd[index] = command_line; + } + + SetInjectedGames( games, cmd); + + if (Settings.UseHook) + { + wxArrayString array; + if (GetHookedGames( array)) array.Empty(); + + int num = array.GetCount(); + for (int i=0; iError_GameIsHooked, "ERROR", wxOK|wxICON_ERROR); + return; + } + } + + STARTUPINFOW si = {0}; + si.cb = sizeof(STARTUPINFO); + PROCESS_INFORMATION pi = {0}; + + wxString path = games[index].BeforeLast('\\'); + wxString exe; + + if (use_cmd) exe << "\"" << games[index] << "\" " << command_line; + else exe = games[index]; + + + bool result = CreateProcess(NULL, (wchar_t*) exe.wc_str(), NULL, NULL, FALSE, + CREATE_SUSPENDED, NULL, path.wc_str(), &si, &pi); + if(!result) + { + wxMessageBox( Language->Error_ProcessNotStarted, "ERROR", wxOK|wxICON_ERROR); + return ; + } + + + wxString dll = wxGetCwd(); + dll.Append( L"\\" uMod_d3d9_DI_dll); + + Inject(pi.hProcess, dll.wc_str(), "Nothing"); + ResumeThread(pi.hThread); +} + +void uMod_Frame::OnMenuUseHook(wxCommandEvent& WXUNUSED(event)) +{ + bool use_hook = MenuMain->IsChecked(ID_Menu_UseHook); + + if (Settings.UseHook!=use_hook) + { + if (Settings.UseHook) + { + if (NumberOfGames>0) + { + MenuMain->Check(ID_Menu_UseHook, true); + wxMessageBox(Language->Error_RemoveHook, "ERROR", wxOK|wxICON_ERROR); + return; + } + RemoveHook(); + } + else + { + InstallHook(); + } + Settings.UseHook=use_hook; + } +} + +void uMod_Frame::OnMenuAddGame(wxCommandEvent& WXUNUSED(event)) +{ + wxString file_name = wxFileSelector( Language->ChooseGame, "", "", "exe", "binary (*.exe)|*.exe", wxFD_OPEN | wxFD_FILE_MUST_EXIST, this); + if ( !file_name.empty() ) + { + wxArrayString array; + if (GetHookedGames( array)) array.Empty(); + + int num = array.GetCount(); + for (int i=0; iGameAlreadyAdded, "ERROR", wxOK|wxICON_ERROR); + return; + } + array.Add(file_name); + if (SetHookedGames( array)) + { + wxMessageBox( LastError, "ERROR", wxOK|wxICON_ERROR); + LastError.Empty(); + return; + } + } +} + +void uMod_Frame::OnMenuDeleteGame(wxCommandEvent& WXUNUSED(event)) +{ + wxArrayInt selections; + wxArrayString array; + if (GetHookedGames( array)) + { + wxMessageBox( LastError, "ERROR", wxOK|wxICON_ERROR); + LastError.Empty(); + return; + } + wxGetSelectedChoices( selections, Language->DeleteGame, Language->DeleteGame, array); + + int num = selections.GetCount(); + for (int i=0; iEnable( ID_Menu_LoadTemplate, true); + MenuMain->Enable( ID_Menu_SaveTemplate, true); + MenuMain->Enable( ID_Menu_SaveTemplateAs, true); + MenuMain->Enable( ID_Menu_SetDefaultTemplate, true); + + + OpenButton->Enable( true); + DirectoryButton->Enable( true); + UpdateButton->Enable( true); + ReloadButton->Enable( true); + + return 0; +} + +int uMod_Frame::DeactivateGamesControl(void) +{ + MenuMain->Enable( ID_Menu_LoadTemplate, false); + MenuMain->Enable( ID_Menu_SaveTemplate, false); + MenuMain->Enable( ID_Menu_SaveTemplateAs, false); + MenuMain->Enable( ID_Menu_SetDefaultTemplate, false); + + + OpenButton->Enable( false); + DirectoryButton->Enable( false); + UpdateButton->Enable( false); + ReloadButton->Enable( false); + return 0; +} + +int uMod_Frame::GetHookedGames( wxArrayString &array) +{ + wxFile file; + wxString name; + wchar_t *app_path = _wgetenv( L"APPDATA"); + name.Printf("%ls\\%ls\\%ls", app_path, uMod_APP_DIR, uMod_APP_DX9); + + if (!file.Access(name, wxFile::read)) {LastError << Language->Error_FileOpen << "\n" << name; return -1;} + file.Open(name, wxFile::read); + if (!file.IsOpened()) {LastError << Language->Error_FileOpen << "\n" << name ; return -1;} + + unsigned len = file.Length(); + + unsigned char* buffer; + try {buffer = new unsigned char [len+2];} + catch (...) {LastError << Language->Error_Memory; return -1;} + + unsigned int result = file.Read( buffer, len); + file.Close(); + + if (result != len) {delete [] buffer; LastError << Language->Error_FileRead<<"\n" << name; return -1;} + + wchar_t *buff = (wchar_t*)buffer; + len/=2; + buff[len]=0; + + wxString content; + content = buff; + delete [] buffer; + + wxStringTokenizer token( content, "\n"); + + int num = token.CountTokens(); + + array.Empty(); + + for (int i=0; iError_FileOpen << "\n" << name ; return -1;} + wxString content; + + int num = array.GetCount(); + for (int i=0; iError_FileOpen << "\n" << DI_FILE; return -1;} + file.Open( DI_FILE, wxFile::read); + if (!file.IsOpened()) {LastError << Language->Error_FileOpen << "\n" << DI_FILE ; return -1;} + + unsigned len = file.Length(); + + unsigned char* buffer; + try {buffer = new unsigned char [len+2];} + catch (...) {LastError << Language->Error_Memory; return -1;} + + unsigned int result = file.Read( buffer, len); + file.Close(); + + if (result != len) {delete [] buffer; LastError << Language->Error_FileRead<<"\n" << DI_FILE; return -1;} + + wchar_t *buff = (wchar_t*)buffer; + len/=2; + buff[len]=0; + + wxString content; + content = buff; + delete [] buffer; + + wxStringTokenizer token( content, "\n"); + + int num = token.CountTokens(); + + games.Empty(); + games.Alloc(num); + cmd.Empty(); + cmd.Alloc(num); + wxString entry; + + for (int i=0; iError_FileOpen << "\n" << DI_FILE ; return -1;} + wxString content; + + int num = games.GetCount(); + for (int i=0; iError_FileOpen << "\n" << SAVE_FILE; return -1;} + file.Open(SAVE_FILE, wxFile::read); + if (!file.IsOpened()) {LastError << Language->Error_FileOpen << "\n" << SAVE_FILE ; return -1;} + + unsigned len = file.Length(); + + unsigned char* buffer; + try {buffer = new unsigned char [len+2];} + catch (...) {LastError << Language->Error_Memory; return -1;} + + unsigned int result = file.Read( buffer, len); + file.Close(); + + if (result != len) {delete [] buffer; LastError << Language->Error_FileRead<<"\n" << SAVE_FILE; return -1;} + + wchar_t *buff = (wchar_t*)buffer; + len/=2; + buff[len]=0; + + wxString content; + content = buff; + delete [] buffer; + + wxStringTokenizer token( content, "\n"); + + int num = token.CountTokens(); + + SaveFile_Exe.Empty(); + SaveFile_Exe.Alloc(num+10); + SaveFile_Name.Empty(); + SaveFile_Name.Alloc(num+10); + + wxString line; + wxString exe; + wxString name; + for (int i=0; iError_FileOpen << "\n" << SAVE_FILE ; return -1;} + wxString content; + + int num = SaveFile_Exe.GetCount(); + for (int i=0; iError_DLLNotFound; + temp << "\n" << uMod_d3d9_Hook_dll; + temp << "\n" << error_msg << "Code: " << error; + wxMessageBox( temp, "ERROR", wxOK); + } + } + else + { + DWORD error = GetLastError(); + wchar_t *error_msg; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &error_msg, 0, NULL ); + wxString temp = Language->Error_DLLNotFound; + temp << "\n" << uMod_d3d9_Hook_dll; + temp << "\n" << error_msg << "Code: " << error; + wxMessageBox(temp, "ERROR", wxOK|wxICON_ERROR); + } + } +} + +void uMod_Frame::RemoveHook(void) +{ + if (H_DX9_DLL!=NULL) + { + typedef void (*fkt_typ)(void); + fkt_typ remove_hook = (fkt_typ) GetProcAddress( H_DX9_DLL, "RemoveHook"); + if (remove_hook!=NULL) remove_hook(); + FreeLibrary(H_DX9_DLL); + } + H_DX9_DLL = NULL; +} diff --git a/uMod2/uMod_GUI/uMod_GUI.h b/uMod2/uMod_GUI/uMod_GUI.h new file mode 100644 index 0000000..3a47af1 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_GUI.h @@ -0,0 +1,129 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_GUI_H_ +#define uMod_GUI_H_ + + +#include "uMod_Main.h" + +class uMod_Frame : public wxFrame +{ +public: + uMod_Frame(const wxString& title, uMod_Settings &set); + ~uMod_Frame(void); + + + + void OnAddGame( wxCommandEvent &event); + void OnDeleteGame( wxCommandEvent &event); + + void OnClose(wxCloseEvent& WXUNUSED(event)); + + + void OnButtonOpen(wxCommandEvent& WXUNUSED(event)); + void OnButtonPath(wxCommandEvent& WXUNUSED(event)); + void OnButtonUpdate(wxCommandEvent& WXUNUSED(event)); + void OnButtonReload(wxCommandEvent& WXUNUSED(event)); + + void OnMenuStartGame( wxCommandEvent &event); + + void OnMenuUseHook( wxCommandEvent &event); + void OnMenuAddGame(wxCommandEvent& WXUNUSED(event)); + void OnMenuDeleteGame(wxCommandEvent& WXUNUSED(event)); + + void OnMenuOpenTemplate(wxCommandEvent& WXUNUSED(event)); + void OnMenuSaveTemplate(wxCommandEvent& WXUNUSED(event)); + void OnMenuSaveTemplateAs(wxCommandEvent& WXUNUSED(event)); + void OnMenuSetDefaultTemplate(wxCommandEvent& WXUNUSED(event)); + void OnMenuLanguage(wxCommandEvent& WXUNUSED(event)); + + void OnMenuExit(wxCommandEvent& WXUNUSED(event)); + + void OnMenuHelp(wxCommandEvent& WXUNUSED(event)); + void OnMenuAbout(wxCommandEvent& WXUNUSED(event)); + void OnMenuAcknowledgement(wxCommandEvent& WXUNUSED(event)); + +private: + + int ActivateGamesControl(void); + int DeactivateGamesControl(void); + + uMod_Settings Settings; + int KillServer(void); + int GetHookedGames( wxArrayString &array); + int SetHookedGames( const wxArrayString &array); + + int GetInjectedGames( wxArrayString &games, wxArrayString &cmd); + int SetInjectedGames( wxArrayString &games, wxArrayString &cmd); + + uMod_Server *Server; + + wxNotebook *Notebook; + + + wxButton *OpenButton; + wxButton *DirectoryButton; + wxButton *UpdateButton; + wxButton *ReloadButton; + + + wxMenuBar *MenuBar; + wxMenu *MenuMain; + wxMenu *MenuHelp; + + wxBoxSizer *MainSizer; + wxBoxSizer *ButtonSizer; + + + int NumberOfGames; + int MaxNumberOfGames; + uMod_Client **Clients; + + int LoadTemplate(void); + int SaveTemplate(void); + wxArrayString SaveFile_Exe; + wxArrayString SaveFile_Name; + + + void InstallHook(void); + void RemoveHook(void); + + HMODULE H_DX9_DLL; + + wxString LastError; + + DECLARE_EVENT_TABLE(); +}; + +class MyApp : public wxApp +{ +public: + virtual ~MyApp(); + virtual bool OnInit(); + +private: + HANDLE CheckForSingleRun; +}; + + + + +#endif diff --git a/uMod2/uMod_GUI/uMod_GameInfo.cpp b/uMod2/uMod_GUI/uMod_GameInfo.cpp new file mode 100644 index 0000000..7a5699c --- /dev/null +++ b/uMod2/uMod_GUI/uMod_GameInfo.cpp @@ -0,0 +1,333 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + + +uMod_GameInfo::uMod_GameInfo(void) +{ + Checked = NULL; + NumberOfChecked = 0; + LengthOfChecked = 0; + Init(); +} + + +uMod_GameInfo::~uMod_GameInfo(void) +{ + if (Checked!=NULL) delete [] Checked; +} + +void uMod_GameInfo::Init(void) +{ + SaveSingleTexture = false; + SaveAllTextures = false; + + KeyBack = -1; + KeySave = -1; + KeyNext = -1; + FontColour[0]=255;FontColour[1]=0;FontColour[2]=0; + TextureColour[0]=0;TextureColour[1]=255;TextureColour[2]=0; + NumberOfChecked = 0; + SavePath.Empty(); + OpenPath.Empty(); + Files.Empty(); +} + +int uMod_GameInfo::SaveToFile( const wxString &file_name) +{ + wxFile file; + + //if (!file.Access(name, wxFile::write)) return -1; + file.Open(file_name, wxFile::write); + if (!file.IsOpened()) {return -1;} + + wxString content; + if (SavePath.Len()>0) + { + content.Printf( L"SavePath:%ls\n", SavePath.wc_str()); + file.Write( content.char_str(), content.Len()); + } + + if (OpenPath.Len()>0) + { + content.Printf( L"OpenPath:%ls\n", OpenPath.wc_str()); + file.Write( content.char_str(), content.Len()); + } + + content.Printf( L"SaveAllTextures:%d\nSaveSingleTexture:%d\n", SaveAllTextures, SaveSingleTexture); + file.Write( content.char_str(), content.Len()); + + if (KeyBack>=0) + { + content.Printf( L"KeyBack:%d\n", KeyBack); + file.Write( content.char_str(), content.Len()); + } + if (KeySave>=0) + { + content.Printf( L"KeySave:%d\n", KeySave); + file.Write( content.char_str(), content.Len()); + } + if (KeyNext>=0) + { + content.Printf( L"KeyNext:%d\n", KeyNext); + file.Write( content.char_str(), content.Len()); + } + + content.Printf( L"FontColour:%d,%d,%d\n", FontColour[0], FontColour[1], FontColour[2]); + file.Write( content.char_str(), content.Len()); + content.Printf( L"TextureColour:%d,%d,%d\n", TextureColour[0], TextureColour[1], TextureColour[2]); + file.Write( content.char_str(), content.Len()); + + int num = Files.GetCount(); + + for (int i=0; i=LengthOfChecked) + { + bool *t_bool; + try {t_bool = new bool [LengthOfChecked+100];} + catch (...) {return -1;} + for (int i=0; iLengthOfChecked) + { + if (Checked!=NULL) delete [] Checked; + try {Checked = new bool [num+100];} + catch (...) {Checked=NULL; LengthOfChecked = 0; return -1;} + LengthOfChecked = num+100; + } + for (int i=0; i. +*/ + + + +#ifndef uMod_GAME_H_ +#define uMod_GAME_H_ +#include "uMod_Main.h" + +//this class is intended as a storing object for each game +// one should ad an assignment operator, loading and saving default values, ... +class uMod_GameInfo +{ +public: + uMod_GameInfo(void); + ~uMod_GameInfo(void); + void Init(void); + + + int SaveToFile( const wxString &file_name); + int LoadFromFile( const wxString &file_name); + + int GetChecked( bool* array, int num) const; + int SetChecked( bool* array, int num); + + int SetSaveSingleTexture(bool val); + bool GetSaveSingleTexture(void) const {return SaveSingleTexture;} + + int SetSaveAllTextures(bool val); + bool GetSaveAllTextures(void) const {return SaveAllTextures;} + + void SetFiles(const wxArrayString &files); + void GetFiles( wxArrayString &files) const; + //void AddTexture( const wxString &textures); + + int GetNumberOfFiles(void) const {return Files.GetCount();} + + int SendTextures(void); + + int GetKeyBack() const {return KeyBack;} + int SetKeyBack(int key) {KeyBack=key; return 0;} + + int GetKeySave() const {return KeySave;} + int SetKeySave(int key) {KeySave=key; return 0;} + + int GetKeyNext() const {return KeyNext;} + int SetKeyNext(int key) {KeyNext=key; return 0;} + + int SetFontColour(const int *colour) {FontColour[0]=colour[0];FontColour[1]=colour[1];FontColour[2]=colour[2];return 0;} + int GetFontColour(int *colour) const {colour[0]=FontColour[0];colour[1]=FontColour[1];colour[2]=FontColour[2];return 0;} + + int SetTextureColour(const int *colour) {TextureColour[0]=colour[0];TextureColour[1]=colour[1];TextureColour[2]=colour[2];return 0;} + int GetTextureColour(int *colour) const {colour[0]=TextureColour[0];colour[1]=TextureColour[1];colour[2]=TextureColour[2];return 0;} + + int SetOpenPath(const wxString &path) {OpenPath=path; return 0;} + wxString GetOpenPath(void) const {return OpenPath;} + + int SetSavePath(const wxString &path) {SavePath=path; return 0;} + wxString GetSavePath(void) const {return SavePath;} + + uMod_GameInfo& operator = (const uMod_GameInfo &rhs); + +private: + + bool *Checked; + int NumberOfChecked; + int LengthOfChecked; + + bool SaveSingleTexture; + bool SaveAllTextures; + + wxArrayString Files; + + int KeyBack; + int KeySave; + int KeyNext; + + int FontColour[3]; + int TextureColour[3]; + + wxString OpenPath; + wxString SavePath; +}; + + +#endif /* uMod_SERVER_H_ */ diff --git a/uMod2/uMod_GUI/uMod_GamePage.cpp b/uMod2/uMod_GUI/uMod_GamePage.cpp new file mode 100644 index 0000000..34b330a --- /dev/null +++ b/uMod2/uMod_GUI/uMod_GamePage.cpp @@ -0,0 +1,525 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +#include "uMod_Main.h" + + +uMod_GamePage::uMod_GamePage( wxNotebook *parent, const wxString &exe, const wxString &save, PipeStruct &pipe) + : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL), Sender(pipe) +{ + ExeName = exe; + TemplateName = save; + + //SetBackgroundColour( *wxLIGHT_GREY); + //SetBackgroundColour( wxColour( "LIGHT GREY")); + + CheckBoxHSizers = NULL; + CheckButtonUp = NULL; + CheckButtonDown = NULL; + CheckButtonDelete = NULL; + CheckBoxes = NULL; + + MainSizer = new wxBoxSizer(wxVERTICAL); + + + TemplateFile = new wxTextCtrl(this, wxID_ANY, Language->TextCtrlTemplate, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + MainSizer->Add( (wxWindow*) TemplateFile, 0, wxEXPAND, 0); + MainSizer->AddSpacer(10); + + SizerKeys[0] = new wxBoxSizer(wxHORIZONTAL); + SizerKeys[1] = new wxBoxSizer(wxHORIZONTAL); + + TextKeyBack = new wxTextCtrl(this, wxID_ANY, Language->KeyBack, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + SizerKeys[0]->Add( (wxWindow*) TextKeyBack, 1, wxEXPAND, 0); + ChoiceKeyBack = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Language->KeyStrings); + SizerKeys[1]->Add( (wxWindow*) ChoiceKeyBack, 1, wxEXPAND, 0); + + TextKeySave = new wxTextCtrl(this, wxID_ANY, Language->KeySave, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + SizerKeys[0]->Add( (wxWindow*) TextKeySave, 1, wxEXPAND, 0); + ChoiceKeySave = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Language->KeyStrings); + SizerKeys[1]->Add( (wxWindow*) ChoiceKeySave, 1, wxEXPAND, 0); + + TextKeyNext = new wxTextCtrl(this, wxID_ANY, Language->KeyNext, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + SizerKeys[0]->Add( (wxWindow*) TextKeyNext, 1, wxEXPAND, 0); + ChoiceKeyNext = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Language->KeyStrings); + SizerKeys[1]->Add( (wxWindow*) ChoiceKeyNext, 1, wxEXPAND, 0); + + MainSizer->Add( SizerKeys[0], 0, wxEXPAND, 0); + MainSizer->Add( SizerKeys[1], 0, wxEXPAND, 0); + + + FontColourSizer = new wxBoxSizer(wxHORIZONTAL); + FontColour[0] = new wxTextCtrl(this, wxID_ANY, Language->FontColour, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + FontColour[1] = new wxTextCtrl(this, wxID_ANY, "255", wxDefaultPosition, wxDefaultSize); + FontColour[2] = new wxTextCtrl(this, wxID_ANY, "0", wxDefaultPosition, wxDefaultSize); + FontColour[3] = new wxTextCtrl(this, wxID_ANY, "0", wxDefaultPosition, wxDefaultSize); + for (int i=0; i<4; i++) FontColourSizer->Add( (wxWindow*) FontColour[i], 1, wxEXPAND, 0); + + TextureColourSizer = new wxBoxSizer(wxHORIZONTAL); + TextureColour[0] = new wxTextCtrl(this, wxID_ANY, Language->TextureColour, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + TextureColour[1] = new wxTextCtrl(this, wxID_ANY, "0", wxDefaultPosition, wxDefaultSize); + TextureColour[2] = new wxTextCtrl(this, wxID_ANY, "255", wxDefaultPosition, wxDefaultSize); + TextureColour[3] = new wxTextCtrl(this, wxID_ANY, "0", wxDefaultPosition, wxDefaultSize); + for (int i=0; i<4; i++) TextureColourSizer->Add( (wxWindow*) TextureColour[i], 1, wxEXPAND, 0); + + + MainSizer->Add( FontColourSizer, 0, wxEXPAND, 0); + MainSizer->Add( TextureColourSizer, 0, wxEXPAND, 0); + + SaveSingleTexture = new wxCheckBox( this, -1, Language->CheckBoxSaveSingleTexture); + MainSizer->Add( (wxWindow*) SaveSingleTexture, 0, wxEXPAND, 0); + + SaveAllTextures = new wxCheckBox( this, -1, Language->CheckBoxSaveAllTextures); + MainSizer->Add( (wxWindow*) SaveAllTextures, 0, wxEXPAND, 0); + + SavePath = new wxTextCtrl(this, wxID_ANY, Language->TextCtrlSavePath, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); + MainSizer->Add( (wxWindow*) SavePath, 0, wxEXPAND, 0); + + MainSizer->AddSpacer(10); + + NumberOfEntry = 0; + MaxNumberOfEntry = 1024; + if (GetMemory( CheckBoxes, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return;} + if (GetMemory( CheckBoxHSizers, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return ;} + if (GetMemory( CheckButtonUp, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return;} + if (GetMemory( CheckButtonDown, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return;} + if (GetMemory( CheckButtonDelete, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return;} + SavePath->SetValue(Language->TextCtrlSavePath); + + + SetSizer(MainSizer); + + SetScrollRate(0, 20); + MainSizer->FitInside(this); + + if (TemplateName.Len()>0) LoadTemplate(TemplateName); +} + +uMod_GamePage::~uMod_GamePage(void) +{ + for (int i=0; iTextCtrlSavePath; + save_path << path; + SavePath->SetValue(save_path); + Game.SetSavePath( path); + return 0; +} + + +int uMod_GamePage::AddTexture( const wxString &file_name) +{ + if (NumberOfEntry>=MaxNumberOfEntry) + { + if (GetMoreMemory( CheckBoxes, MaxNumberOfEntry, MaxNumberOfEntry+1024)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckBoxHSizers, MaxNumberOfEntry, MaxNumberOfEntry+1024)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonUp, MaxNumberOfEntry, MaxNumberOfEntry+1024)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonDown, MaxNumberOfEntry, MaxNumberOfEntry+1024)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonDelete, MaxNumberOfEntry, MaxNumberOfEntry+1024)) {LastError = Language->Error_Memory; return -1;} + MaxNumberOfEntry+=1024; + } + uMod_File file( file_name); + if (!file.FileSupported()) {LastError << Language->Error_FileNotSupported << "\n" << file_name; return -1;} + + wxString tool_tip; + file.GetComment( tool_tip); + + CheckBoxHSizers[NumberOfEntry] = new wxBoxSizer(wxHORIZONTAL); + CheckBoxes[NumberOfEntry] = new wxCheckBox( this, -1, file_name); + CheckBoxes[NumberOfEntry]->SetValue( true); + CheckBoxes[NumberOfEntry]->SetToolTip( tool_tip); + + wchar_t button_txt[2]; + button_txt[0] = 8657; + button_txt[1] = 0; + CheckButtonUp[NumberOfEntry] = new wxButton( this, ID_Button_Texture+3*NumberOfEntry, button_txt, wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonUp, this, ID_Button_Texture+3*NumberOfEntry); + + button_txt[0] = 8659; + CheckButtonDown[NumberOfEntry] = new wxButton( this, ID_Button_Texture+3*NumberOfEntry+1, button_txt, wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDown, this, ID_Button_Texture+3*NumberOfEntry+1); + + CheckButtonDelete[NumberOfEntry] = new wxButton( this, ID_Button_Texture+3*NumberOfEntry+2, L"X", wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDelete, this, ID_Button_Texture+3*NumberOfEntry+2); + + CheckBoxHSizers[NumberOfEntry]->Add( (wxWindow*) CheckBoxes[NumberOfEntry], 1, wxEXPAND, 0); + CheckBoxHSizers[NumberOfEntry]->Add( (wxWindow*) CheckButtonUp[NumberOfEntry], 0, wxEXPAND, 0); + CheckBoxHSizers[NumberOfEntry]->Add( (wxWindow*) CheckButtonDown[NumberOfEntry], 0, wxEXPAND, 0); + CheckBoxHSizers[NumberOfEntry]->Add( (wxWindow*) CheckButtonDelete[NumberOfEntry], 0, wxEXPAND, 0); + + MainSizer->Add( CheckBoxHSizers[NumberOfEntry], 0, wxEXPAND, 0); + Files.Add( file_name); + NumberOfEntry++; + MainSizer->Layout(); + MainSizer->FitInside(this); + + return UpdateGame(); +} + +int uMod_GamePage::GetSettings(void) +{ + int key_back = ChoiceKeyBack->GetSelection(); + int key_save = ChoiceKeySave->GetSelection(); + int key_next = ChoiceKeyNext->GetSelection(); + + if (key_back==key_save && key_back!=wxNOT_FOUND) {LastError << Language->Error_KeyTwice; return 1;} + if (key_back==key_next && key_back!=wxNOT_FOUND) {LastError << Language->Error_KeyTwice; return 1;} + if (key_save==key_next && key_save!=wxNOT_FOUND) {LastError << Language->Error_KeyTwice; return 1;} + + bool save_single = SaveSingleTexture->GetValue(); + bool save_all = SaveAllTextures->GetValue(); + wxString path = Game.GetSavePath(); + if ( (save_single || save_all) && path.Len()==0) {LastError << Language->Error_NoSavePath; return 1;} + + if ( save_single && ( key_back==wxNOT_FOUND || key_save==wxNOT_FOUND || key_next==wxNOT_FOUND) ) {LastError << Language->Error_KeyNotSet; return 1;} + + if (key_back!=wxNOT_FOUND) Game.SetKeyBack(key_back); + if (key_save!=wxNOT_FOUND) Game.SetKeySave(key_save); + if (key_next!=wxNOT_FOUND) Game.SetKeyNext(key_next); + + Game.SetSaveSingleTexture( save_single); + Game.SetSaveAllTextures( save_all); + + int colour[3]; + colour[0] = GetColour( FontColour[1], 255); + colour[1] = GetColour( FontColour[2], 0); + colour[2] = GetColour( FontColour[3], 0); + SetColour( &FontColour[1], colour); + Game.SetFontColour(colour); + + colour[0] = GetColour( TextureColour[1], 0); + colour[1] = GetColour( TextureColour[2], 255); + colour[2] = GetColour( TextureColour[3], 0); + SetColour( &TextureColour[1], colour); + Game.SetTextureColour(colour); + + Game.SetFiles( Files); + + bool *checked = NULL; + if (GetMemory( checked, NumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + for (int i=0; iGetValue(); + Game.SetChecked( checked, NumberOfEntry); + delete [] checked; + + return 0; +} + +int uMod_GamePage::UpdateGame(void) +{ + if (int ret = GetSettings()) return ret; + + if (int ret = Sender.Send( Game, GameOld, false)) + { + LastError = Language->Error_Send; + LastError << "\n" << Sender.LastError; + Sender.LastError.Empty(); + return ret; + } + + GameOld = Game; + return 0; +} + + +int uMod_GamePage::ReloadGame(void) +{ + if (int ret = GetSettings()) return ret; + + if (int ret = Sender.Send( Game, GameOld, true)) + { + LastError = Language->Error_Send; + LastError << "\n" << Sender.LastError; + Sender.LastError.Empty(); + return ret; + } + + GameOld = Game; + return 0; +} + +int uMod_GamePage::SaveTemplate( const wxString &file_name) +{ + if (int ret = GetSettings()) return ret; + if (int ret = Game.SaveToFile( file_name)) + { + LastError = Language->Error_SaveFile; + LastError <<"\n" << file_name; + return ret; + } + TemplateName = file_name; + wxString path; + path = Language->TextCtrlTemplate; + path << TemplateName; + TemplateFile->SetValue( path); + + return 0; +} + +int uMod_GamePage::LoadTemplate( const wxString &file_name) +{ + if (Game.LoadFromFile(file_name)) return -1; + TemplateName = file_name; + wxArrayString comments; + + if (Sender.Send( Game, GameOld, true, &comments)==0) GameOld = Game; + + wxString path; + path = Language->TextCtrlTemplate; + path << TemplateName; + TemplateFile->SetValue( path); + + int key = Game.GetKeyBack(); + if (key>=0) ChoiceKeyBack->SetSelection( key); + key = Game.GetKeySave(); + if (key>=0) ChoiceKeySave->SetSelection( key); + key = Game.GetKeyNext(); + if (key>=0) ChoiceKeyNext->SetSelection( key); + + int colour[3]; + Game.GetFontColour( colour); + SetColour( &FontColour[1], colour); + Game.GetTextureColour( colour); + SetColour( &TextureColour[1], colour); + + SaveSingleTexture->SetValue( Game.GetSaveSingleTexture()); + SaveAllTextures->SetValue( Game.GetSaveAllTextures()); + + path = Language->TextCtrlSavePath; + path << Game.GetSavePath(); + SavePath->SetValue( path); + + int new_NumberOfEntry = Game.GetNumberOfFiles(); + + Game.GetFiles( Files); + + if (new_NumberOfEntry>=MaxNumberOfEntry) + { + MaxNumberOfEntry = ((NumberOfEntry/1024)+1)*1024; + if (GetMoreMemory( CheckBoxes, NumberOfEntry, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckBoxHSizers, NumberOfEntry, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonUp, NumberOfEntry, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonDown, NumberOfEntry, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + if (GetMoreMemory( CheckButtonDelete, NumberOfEntry, MaxNumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + } + + bool *checked = NULL; + if (GetMemory( checked, new_NumberOfEntry)) {LastError = Language->Error_Memory; return -1;} + Game.GetChecked( checked, new_NumberOfEntry); + + + for (int i=0; iSetLabel( Files[i]); + CheckBoxes[i]->SetValue( checked[i]); + CheckBoxes[i]->SetToolTip( comments[i]); + } + + for (int i=new_NumberOfEntry; iDetach( (wxWindow*) CheckBoxes[i]); + CheckBoxHSizers[i]->Detach( (wxWindow*) CheckButtonUp[i]); + CheckBoxHSizers[i]->Detach( (wxWindow*) CheckButtonDown[i]); + CheckBoxHSizers[i]->Detach( (wxWindow*) CheckButtonDelete[i]); + + MainSizer->Detach( CheckBoxHSizers[i]); + + delete CheckBoxes[i]; + delete CheckButtonUp[i]; + delete CheckButtonDown[i]; + delete CheckButtonDelete[i]; + delete CheckBoxHSizers[i]; + } + for (int i=NumberOfEntry; iSetValue( checked[i]); + CheckBoxes[i]->SetToolTip( comments[i]); + + wchar_t button_txt[2]; + button_txt[0] = 8657; + button_txt[1] = 0; + + CheckButtonUp[i] = new wxButton( this, ID_Button_Texture+3*i, button_txt, wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonUp, this, ID_Button_Texture+3*i); + + button_txt[0] = 8659; + CheckButtonDown[i] = new wxButton( this, ID_Button_Texture+3*i+1, button_txt, wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDown, this, ID_Button_Texture+3*i+1); + + CheckButtonDelete[i] = new wxButton( this, ID_Button_Texture+3*i+2, L"X", wxDefaultPosition, wxSize(24,24)); + Bind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDelete, this, ID_Button_Texture+3*i+2); + + CheckBoxHSizers[i]->Add( (wxWindow*) CheckBoxes[i], 1, wxEXPAND, 0); + CheckBoxHSizers[i]->Add( (wxWindow*) CheckButtonUp[i], 0, wxEXPAND, 0); + CheckBoxHSizers[i]->Add( (wxWindow*) CheckButtonDown[i], 0, wxEXPAND, 0); + CheckBoxHSizers[i]->Add( (wxWindow*) CheckButtonDelete[i], 0, wxEXPAND, 0); + + MainSizer->Add( CheckBoxHSizers[i], 0, wxEXPAND, 0); + } + delete [] checked; + NumberOfEntry = new_NumberOfEntry; + + MainSizer->Layout(); + MainSizer->FitInside(this); + return 0; +} + +int uMod_GamePage::SetColour( wxTextCtrl** txt, int *colour) +{ + wxString temp; + for (int i=0; i<3; i++) + { + temp.Empty(); + temp << colour[i]; + txt[i]->SetValue( temp); + } + return 0; +} + +int uMod_GamePage::GetColour( wxTextCtrl* txt, int def) +{ + wxString temp = txt->GetValue(); + long colour; + if (temp.ToLong(&colour)) + { + if (colour<0) colour=0; + else if (colour>255) colour=255; + } + else colour = def; + return colour; +} + + +void uMod_GamePage::OnButtonUp(wxCommandEvent& event) +{ + int id = (event.GetId() - ID_Button_Texture)/3; + if (id <=0 || id>= NumberOfEntry) return; + + wxString cpy_str = Files[id]; + Files[id] = Files[id-1]; + Files[id-1] = cpy_str; + + CheckBoxes[id]->SetLabel(Files[id]); + CheckBoxes[id-1]->SetLabel(Files[id-1]); + + bool cpy_checked = CheckBoxes[id]->GetValue(); + CheckBoxes[id]->SetValue(CheckBoxes[id-1]->GetValue()); + CheckBoxes[id-1]->SetValue(cpy_checked); + + cpy_str = CheckBoxes[id]->GetToolTip()->GetTip(); + wxString cpy_str2 = CheckBoxes[id-1]->GetToolTip()->GetTip(); + CheckBoxes[id]->SetToolTip(cpy_str2); + CheckBoxes[id-1]->SetToolTip(cpy_str); + +} + +void uMod_GamePage::OnButtonDown(wxCommandEvent& event) +{ + int id = (event.GetId() - ID_Button_Texture-1)/3; + if (id <0 || id>= NumberOfEntry-1) return; + + wxString cpy_str = Files[id]; + Files[id] = Files[id+1]; + Files[id+1] = cpy_str; + + CheckBoxes[id]->SetLabel(Files[id]); + CheckBoxes[id+1]->SetLabel(Files[id+1]); + + bool cpy_checked = CheckBoxes[id]->GetValue(); + CheckBoxes[id]->SetValue(CheckBoxes[id+1]->GetValue()); + CheckBoxes[id+1]->SetValue(cpy_checked); + + cpy_str = CheckBoxes[id]->GetToolTip()->GetTip(); + wxString cpy_str2 = CheckBoxes[id+1]->GetToolTip()->GetTip(); + CheckBoxes[id]->SetToolTip(cpy_str2); + CheckBoxes[id+1]->SetToolTip(cpy_str); +} + +void uMod_GamePage::OnButtonDelete(wxCommandEvent& event) +{ + int id = (event.GetId() - ID_Button_Texture-2)/3; + if (id <0 || id>= NumberOfEntry) return; + + for (int i=id+1; iSetLabel(Files[i]); + for (int i=id+1; iSetValue(CheckBoxes[i]->GetValue()); + wxString cpy_str; + for (int i=id+1; iGetToolTip()->GetTip(); + CheckBoxes[i-1]->SetToolTip(cpy_str); + } + + Files.RemoveAt(id, 1); + NumberOfEntry--; + + + Unbind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonUp, this, ID_Button_Texture+3*NumberOfEntry); + Unbind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDown, this, ID_Button_Texture+3*NumberOfEntry+1); + Unbind( wxEVT_COMMAND_BUTTON_CLICKED, &uMod_GamePage::OnButtonDelete, this, ID_Button_Texture+3*NumberOfEntry+2); + + + CheckBoxHSizers[NumberOfEntry]->Detach( (wxWindow*) CheckBoxes[NumberOfEntry]); + CheckBoxHSizers[NumberOfEntry]->Detach( (wxWindow*) CheckButtonUp[NumberOfEntry]); + CheckBoxHSizers[NumberOfEntry]->Detach( (wxWindow*) CheckButtonDown[NumberOfEntry]); + CheckBoxHSizers[NumberOfEntry]->Detach( (wxWindow*) CheckButtonDelete[NumberOfEntry]); + + MainSizer->Detach( CheckBoxHSizers[NumberOfEntry]); + + delete CheckBoxes[NumberOfEntry]; + delete CheckButtonUp[NumberOfEntry]; + delete CheckButtonDown[NumberOfEntry]; + delete CheckButtonDelete[NumberOfEntry]; + delete CheckBoxHSizers[NumberOfEntry]; +} + + +int uMod_GamePage::UpdateLanguage(void) +{ + TextKeyBack->SetValue( Language->KeyBack); + TextKeySave->SetValue( Language->KeySave); + TextKeyNext->SetValue( Language->KeyNext); + FontColour[0]->SetValue( Language->FontColour); + TextureColour[0]->SetValue( Language->TextureColour); + SaveAllTextures->SetLabel( Language->CheckBoxSaveAllTextures); + SaveSingleTexture->SetLabel( Language->CheckBoxSaveSingleTexture); + wxString temp = Language->TextCtrlSavePath; + temp << Game.GetSavePath(); + SavePath->SetValue( temp); + return 0; +} + diff --git a/uMod2/uMod_GUI/uMod_GamePage.h b/uMod2/uMod_GUI/uMod_GamePage.h new file mode 100644 index 0000000..d1bc27e --- /dev/null +++ b/uMod2/uMod_GUI/uMod_GamePage.h @@ -0,0 +1,107 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_GAMEPAGE_H_ +#define uMod_GAMEPAGE_H_ +#include "uMod_Main.h" + +// this page is opened if a game is started. +class uMod_GamePage : public wxScrolledWindow +{ +public: + uMod_GamePage( wxNotebook *parent, const wxString &exe, const wxString &save, PipeStruct &pipe); + virtual ~uMod_GamePage(void); + + int AddTexture( const wxString &file_name); + + int UpdateGame(void); + int ReloadGame(void); + + int SaveTemplate( const wxString &file_name); + int LoadTemplate( const wxString &file_name); + + wxString GetExeName(void) {return ExeName;} + wxString GetTemplateName(void) {return TemplateName;} + + int SetOpenPath(const wxString &path) {return Game.SetOpenPath(path);} + wxString GetOpenPath(void) {return Game.GetOpenPath();} + + int SetSavePath(const wxString &path); + wxString GetSavePath(void) {return Game.GetSavePath();} + + + void OnButtonUp(wxCommandEvent& WXUNUSED(event)); + void OnButtonDown(wxCommandEvent& WXUNUSED(event)); + void OnButtonDelete(wxCommandEvent& WXUNUSED(event)); + + int UpdateLanguage(void); + + wxString LastError; + +private: + + int GetSettings(void); + int SetColour( wxTextCtrl** txt, int *colour); + int GetColour( wxTextCtrl* txt, int def); + + wxString ExeName; + wxString TemplateName; + + wxBoxSizer *SizerKeys[2]; + wxTextCtrl *TextKeyBack; + wxTextCtrl *TextKeySave; + wxTextCtrl *TextKeyNext; + wxChoice *ChoiceKeyBack; + wxChoice *ChoiceKeySave; + wxChoice *ChoiceKeyNext; + + wxBoxSizer *FontColourSizer; + wxTextCtrl *FontColour[4]; + wxBoxSizer *TextureColourSizer; + wxTextCtrl *TextureColour[4]; + + wxBoxSizer *MainSizer; + + wxTextCtrl *TemplateFile; + wxCheckBox *SaveAllTextures; + wxCheckBox *SaveSingleTexture; + wxTextCtrl *SavePath; + + wxBoxSizer **CheckBoxHSizers; + wxButton **CheckButtonUp; + wxButton **CheckButtonDown; + wxButton **CheckButtonDelete; + + wxCheckBox **CheckBoxes; + int NumberOfEntry; + int MaxNumberOfEntry; + + + wxArrayString Files; + uMod_GameInfo Game; + uMod_GameInfo GameOld; + + uMod_Sender Sender; + + + //DECLARE_EVENT_TABLE(); +}; + +#endif /* uMod_GAMEPAGE_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Language.cpp b/uMod2/uMod_GUI/uMod_Language.cpp new file mode 100644 index 0000000..7fbc7f9 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Language.cpp @@ -0,0 +1,727 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + +uMod_Language *Language = NULL; + +uMod_Language::uMod_Language(void) +{ + LoadDefault(); + LoadKeys(); +} + +uMod_Language::uMod_Language(const wxString &name) +{ + LoadLanguage(name); + LoadKeys(); + LastError.Empty(); +} + + +int uMod_Language::GetLanguages(wxArrayString &lang) +{ + wxArrayString files; + wxString dir = wxGetCwd(); + dir << "/languages"; + wxDir::GetAllFiles( dir, &files, "uMod_LanguagePack_*.txt"); + wxDir::GetAllFiles( dir, &files, "uMod_LanguagePackU_*.txt"); + lang.Empty(); + lang.Alloc(files.GetCount()+1); + lang.Add("English"); + + wxString temp; + int num = files.GetCount(); + for (int i=0; i= 0x0500) +#define VK_XBUTTON1 0x05 // NOT contiguous with L & RBUTTON +#define VK_XBUTTON2 0x06 // NOT contiguous with L & RBUTTON +#endif // _WIN32_WINNT >= 0x0500 + + +// * 0x07 : unassigned + + */ + AddKey( "VK_BACK", VK_BACK ); + AddKey( "VK_TAB", VK_TAB ); + AddKey( "VK_CLEAR", VK_CLEAR ); + AddKey( "VK_RETURN", VK_RETURN ); + AddKey( "VK_SHIFT", VK_SHIFT ); + AddKey( "VK_CONTROL", VK_CONTROL ); + AddKey( "VK_MENU", VK_MENU ); + AddKey( "VK_PAUSE", VK_PAUSE ); + AddKey( "VK_CAPITAL", VK_CAPITAL ); + //AddKey( ); + //AddKey( ); + //AddKey( ); + //AddKey( ); + /* +#define VK_BACK 0x08 +#define VK_TAB 0x09 + + +// 0x0A - 0x0B : reserved + + +#define VK_CLEAR 0x0C +#define VK_RETURN 0x0D + +#define VK_SHIFT 0x10 +#define VK_CONTROL 0x11 +#define VK_MENU 0x12 +#define VK_PAUSE 0x13 +#define VK_CAPITAL 0x14 + +#define VK_KANA 0x15 +#define VK_HANGEUL 0x15 // old name - should be here for compatibility +#define VK_HANGUL 0x15 +#define VK_JUNJA 0x17 +#define VK_FINAL 0x18 +#define VK_HANJA 0x19 +#define VK_KANJI 0x19 + +*/ + + AddKey( "VK_ESCAPE", VK_ESCAPE ); +/* +#define VK_ESCAPE 0x1B + +#define VK_CONVERT 0x1C +#define VK_NONCONVERT 0x1D +#define VK_ACCEPT 0x1E +#define VK_MODECHANGE 0x1F +*/ + + AddKey( "VK_SPACE", VK_SPACE ); + AddKey( "VK_PRIOR", VK_PRIOR ); + AddKey( "VK_NEXT", VK_NEXT ); + AddKey( "VK_END", VK_END ); + AddKey( "VK_HOME", VK_HOME ); + AddKey( "VK_LEFT", VK_LEFT ); + AddKey( "VK_UP", VK_UP ); + AddKey( "VK_RIGHT", VK_RIGHT ); + AddKey( "VK_DOWN", VK_DOWN ); + AddKey( "VK_SELECT", VK_SELECT ); + AddKey( "VK_PRINT", VK_PRINT ); + AddKey( "VK_EXECUTE", VK_EXECUTE ); + AddKey( "VK_SNAPSHOT", VK_SNAPSHOT ); + AddKey( "VK_INSERT", VK_INSERT ); + AddKey( "VK_DELETE", VK_DELETE ); + AddKey( "VK_HELP", VK_HELP ); +/* +#define VK_SPACE 0x20 +#define VK_PRIOR 0x21 +#define VK_NEXT 0x22 +#define VK_END 0x23 +#define VK_HOME 0x24 +#define VK_LEFT 0x25 +#define VK_UP 0x26 +#define VK_RIGHT 0x27 +#define VK_DOWN 0x28 +#define VK_SELECT 0x29 +#define VK_PRINT 0x2A +#define VK_EXECUTE 0x2B +#define VK_SNAPSHOT 0x2C +#define VK_INSERT 0x2D +#define VK_DELETE 0x2E +#define VK_HELP 0x2F + + +// * VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) +// * 0x40 : unassigned +// * VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) +*/ + int count = 0x30; + AddKey( "0", count++); + AddKey( "1", count++); + AddKey( "2", count++); + AddKey( "3", count++); + AddKey( "4", count++); + AddKey( "5", count++); + AddKey( "6", count++); + AddKey( "7", count++); + AddKey( "8", count++); + AddKey( "9", count++); + + count = 0x41; + AddKey( "a", count++); + AddKey( "b", count++); + AddKey( "c", count++); + AddKey( "d", count++); + AddKey( "e", count++); + AddKey( "f", count++); + AddKey( "g", count++); + AddKey( "h", count++); + AddKey( "i", count++); + AddKey( "j", count++); + AddKey( "k", count++); + AddKey( "l", count++); + AddKey( "m", count++); + AddKey( "n", count++); + AddKey( "o", count++); + AddKey( "p", count++); + AddKey( "q", count++); + AddKey( "r", count++); + AddKey( "s", count++); + AddKey( "t", count++); + AddKey( "u", count++); + AddKey( "v", count++); + AddKey( "w", count++); + AddKey( "x", count++); + AddKey( "y", count++); + AddKey( "z", count++); + +/* + +#define VK_LWIN 0x5B +#define VK_RWIN 0x5C +#define VK_APPS 0x5D + + +// 0x5E : reserved +*/ + + + AddKey( "VK_SLEEP", VK_SLEEP ); + AddKey( "VK_NUMPAD0", VK_NUMPAD0 ); + AddKey( "VK_NUMPAD1", VK_NUMPAD1 ); + AddKey( "VK_NUMPAD2", VK_NUMPAD2 ); + AddKey( "VK_NUMPAD3", VK_NUMPAD3 ); + AddKey( "VK_NUMPAD4", VK_NUMPAD4 ); + AddKey( "VK_NUMPAD5", VK_NUMPAD5 ); + AddKey( "VK_NUMPAD6", VK_NUMPAD6 ); + AddKey( "VK_NUMPAD7", VK_NUMPAD7 ); + AddKey( "VK_NUMPAD8", VK_NUMPAD8 ); + AddKey( "VK_NUMPAD9", VK_NUMPAD9 ); + AddKey( "VK_MULTIPLY", VK_MULTIPLY ); + AddKey( "VK_ADD", VK_ADD ); + AddKey( "VK_SEPARATOR", VK_SEPARATOR ); + AddKey( "VK_SUBTRACT", VK_SUBTRACT ); + AddKey( "VK_DECIMAL", VK_DECIMAL ); + AddKey( "VK_DIVIDE", VK_DIVIDE ); + AddKey( "VK_F1", VK_F1 ); + AddKey( "VK_F2", VK_F2 ); + AddKey( "VK_F3", VK_F3 ); + AddKey( "VK_F4", VK_F4 ); + AddKey( "VK_F5", VK_F5 ); + AddKey( "VK_F6", VK_F6 ); + AddKey( "VK_F7", VK_F7 ); + AddKey( "VK_F8", VK_F8 ); + AddKey( "VK_F9", VK_F9 ); + AddKey( "VK_F10", VK_F10 ); + AddKey( "VK_F12", VK_F12 ); + AddKey( "VK_F12", VK_F12 ); + + /* + +#define VK_SLEEP 0x5F + +#define VK_NUMPAD0 0x60 +#define VK_NUMPAD1 0x61 +#define VK_NUMPAD2 0x62 +#define VK_NUMPAD3 0x63 +#define VK_NUMPAD4 0x64 +#define VK_NUMPAD5 0x65 +#define VK_NUMPAD6 0x66 +#define VK_NUMPAD7 0x67 +#define VK_NUMPAD8 0x68 +#define VK_NUMPAD9 0x69 +#define VK_MULTIPLY 0x6A +#define VK_ADD 0x6B +#define VK_SEPARATOR 0x6C +#define VK_SUBTRACT 0x6D +#define VK_DECIMAL 0x6E +#define VK_DIVIDE 0x6F +#define VK_F1 0x70 +#define VK_F2 0x71 +#define VK_F3 0x72 +#define VK_F4 0x73 +#define VK_F5 0x74 +#define VK_F6 0x75 +#define VK_F7 0x76 +#define VK_F8 0x77 +#define VK_F9 0x78 +#define VK_F10 0x79 +#define VK_F11 0x7A +#define VK_F12 0x7B +#define VK_F13 0x7C +#define VK_F14 0x7D +#define VK_F15 0x7E +#define VK_F16 0x7F +#define VK_F17 0x80 +#define VK_F18 0x81 +#define VK_F19 0x82 +#define VK_F20 0x83 +#define VK_F21 0x84 +#define VK_F22 0x85 +#define VK_F23 0x86 +#define VK_F24 0x87 + + +// 0x88 - 0x8F : unassigned +*/ + + AddKey( "VK_NUMLOCK", VK_NUMLOCK ); + AddKey( "VK_SCROLL", VK_SCROLL ); +/* + +#define VK_NUMLOCK 0x90 +#define VK_SCROLL 0x91 + + +// NEC PC-9800 kbd definitions + +#define VK_OEM_NEC_EQUAL 0x92 // '=' key on numpad + + +// Fujitsu/OASYS kbd definitions + +#define VK_OEM_FJ_JISHO 0x92 // 'Dictionary' key +#define VK_OEM_FJ_MASSHOU 0x93 // 'Unregister word' key +#define VK_OEM_FJ_TOUROKU 0x94 // 'Register word' key +#define VK_OEM_FJ_LOYA 0x95 // 'Left OYAYUBI' key +#define VK_OEM_FJ_ROYA 0x96 // 'Right OYAYUBI' key + +// +// 0x97 - 0x9F : unassigned +// + +// +// VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. +// Used only as parameters to GetAsyncKeyState() and GetKeyState(). +// No other API or message will distinguish left and right keys in this way. + +#define VK_LSHIFT 0xA0 +#define VK_RSHIFT 0xA1 +#define VK_LCONTROL 0xA2 +#define VK_RCONTROL 0xA3 +#define VK_LMENU 0xA4 +#define VK_RMENU 0xA5 + +#if(_WIN32_WINNT >= 0x0500) +#define VK_BROWSER_BACK 0xA6 +#define VK_BROWSER_FORWARD 0xA7 +#define VK_BROWSER_REFRESH 0xA8 +#define VK_BROWSER_STOP 0xA9 +#define VK_BROWSER_SEARCH 0xAA +#define VK_BROWSER_FAVORITES 0xAB +#define VK_BROWSER_HOME 0xAC + +#define VK_VOLUME_MUTE 0xAD +#define VK_VOLUME_DOWN 0xAE +#define VK_VOLUME_UP 0xAF +#define VK_MEDIA_NEXT_TRACK 0xB0 +#define VK_MEDIA_PREV_TRACK 0xB1 +#define VK_MEDIA_STOP 0xB2 +#define VK_MEDIA_PLAY_PAUSE 0xB3 +#define VK_LAUNCH_MAIL 0xB4 +#define VK_LAUNCH_MEDIA_SELECT 0xB5 +#define VK_LAUNCH_APP1 0xB6 +#define VK_LAUNCH_APP2 0xB7 + +#endif // _WIN32_WINNT >= 0x0500 + + +// 0xB8 - 0xB9 : reserved + + +#define VK_OEM_1 0xBA // ';:' for US +#define VK_OEM_PLUS 0xBB // '+' any country +#define VK_OEM_COMMA 0xBC // ',' any country +#define VK_OEM_MINUS 0xBD // '-' any country +#define VK_OEM_PERIOD 0xBE // '.' any country +#define VK_OEM_2 0xBF // '/?' for US +#define VK_OEM_3 0xC0 // '`~' for US + + +// 0xC1 - 0xD7 : reserved + + +// 0xD8 - 0xDA : unassigned + + +#define VK_OEM_4 0xDB // '[{' for US +#define VK_OEM_5 0xDC // '\|' for US +#define VK_OEM_6 0xDD // ']}' for US +#define VK_OEM_7 0xDE // ''"' for US +#define VK_OEM_8 0xDF + + +// 0xE0 : reserved + + +/ +// Various extended or enhanced keyboards + +#define VK_OEM_AX 0xE1 // 'AX' key on Japanese AX kbd +#define VK_OEM_102 0xE2 // "<>" or "\|" on RT 102-key kbd. +#define VK_ICO_HELP 0xE3 // Help key on ICO +#define VK_ICO_00 0xE4 // 00 key on ICO + +#if(WINVER >= 0x0400) +#define VK_PROCESSKEY 0xE5 +#endif // WINVER >= 0x0400 + +#define VK_ICO_CLEAR 0xE6 + + +#if(_WIN32_WINNT >= 0x0500) +#define VK_PACKET 0xE7 +#endif // _WIN32_WINNT >= 0x0500 + + +// 0xE8 : unassigned + + +//Nokia/Ericsson definitions + +#define VK_OEM_RESET 0xE9 +#define VK_OEM_JUMP 0xEA +#define VK_OEM_PA1 0xEB +#define VK_OEM_PA2 0xEC +#define VK_OEM_PA3 0xED +#define VK_OEM_WSCTRL 0xEE +#define VK_OEM_CUSEL 0xEF +#define VK_OEM_ATTN 0xF0 +#define VK_OEM_FINISH 0xF1 +#define VK_OEM_COPY 0xF2 +#define VK_OEM_AUTO 0xF3 +#define VK_OEM_ENLW 0xF4 +#define VK_OEM_BACKTAB 0xF5 + +#define VK_ATTN 0xF6 +#define VK_CRSEL 0xF7 +#define VK_EXSEL 0xF8 +#define VK_EREOF 0xF9 +#define VK_PLAY 0xFA +#define VK_ZOOM 0xFB +#define VK_NONAME 0xFC +#define VK_PA1 0xFD +#define VK_OEM_CLEAR 0xFE + + + */ + return 0; +} + diff --git a/uMod2/uMod_GUI/uMod_Language.h b/uMod2/uMod_GUI/uMod_Language.h new file mode 100644 index 0000000..3967d49 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Language.h @@ -0,0 +1,128 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_LANGUAGE_H_ +#define uMod_LANGUAGE_H_ + +class uMod_Language +{ +public: + uMod_Language(void); + uMod_Language(const wxString &name); + + + int LoadLanguage(const wxString &name); + int GetLanguages(wxArrayString &lang); + int GetHelpMessage(wxString &help); + wxString GetCurrentLanguage(void) {return CurrentLanguage;} + + wxString MenuLanguage; + wxString MenuHelp; + wxString MenuAbout; + wxString MenuAcknowledgement; + wxString MenuStartGame; + wxString MenuStartGameCMD; + wxString MenuUseHook; + wxString MenuAddGame; + wxString MenuDeleteGame; + wxString MenuLoadTemplate; + wxString MenuSaveTemplate; + wxString MenuSaveTemplateAs; + wxString MenuSetDefaultTemplate; + wxString MenuExit; + + wxString MainMenuMain; + wxString MainMenuHelp; + + wxString ButtonOpen; + wxString ButtonDirectory; + wxString ButtonUpdate; + wxString ButtonReload; + + wxString ChooseFile; + wxString ChooseDir; + + wxString TextCtrlTemplate; + wxString CheckBoxSaveSingleTexture; + wxString CheckBoxSaveAllTextures; + wxString TextCtrlSavePath; + + wxString SelectLanguage; + + wxString StartGame; + wxString CommandLine; + + wxString ChooseGame; + wxString DeleteGame; + wxString GameAlreadyAdded; + wxString ExitGameAnyway; + wxString NoComment; + wxString Author; + + wxString Error_GameIsHooked; + wxString Error_ProcessNotStarted; + wxString Error_RemoveHook; + + wxString Error_FileNotSupported; + wxString Error_FktNotFound; + wxString Error_D3DX9NotFound; + wxString Error_DLLNotFound; + wxString Error_AlreadyRunning; + + wxString Error_Send; + wxString Error_KeyTwice; + wxString Error_NoSavePath; + wxString Error_KeyNotSet; + wxString Error_SaveFile; + wxString Error_NoPipe; + wxString Error_WritePipe; + wxString Error_FlushPipe; + wxString Error_Hash; + wxString Error_FileOpen; + wxString Error_FileRead; + wxString Error_Memory; + wxString Error_Unzip; + wxString Error_ZipEntry; + + wxString KeyBack; + wxString KeySave; + wxString KeyNext; + wxArrayString KeyStrings; + wxArrayInt KeyValues; + + + wxString FontColour; + wxString TextureColour; + + + wxString LastError; + +private: + int LoadDefault(void); + int LoadKeys(void); + + wxString CurrentLanguage; +}; + + +extern uMod_Language *Language; + + +#endif /* uMod_LANGUAGE_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Main.h b/uMod2/uMod_GUI/uMod_Main.h new file mode 100644 index 0000000..9a15bfe --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Main.h @@ -0,0 +1,157 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_MAIN_H_ +#define uMod_MAIN_H_ + + +// I use eclipse and somehow i need these define or many of the wx classes are unknown to the CDT parser +#ifdef __CDT_PARSER__ +#define HAVE_W32API_H +#define __WXMSW__ +#define NOPCH +#define _UNICODE +#define wxUSE_NOTEBOOK 1 +#define wxUSE_CHECKBOX 1 +#define wxUSE_THREADS 1 +#define wxUSE_MSGDLG 1 +#define wxUSE_MENUS 1 +#define wxUSE_BUTTON 1 +#define wxUSE_FILEDLG 1 +#define wxUSE_DIRDLG 1 +#define wxUSE_CHOICE 1 +#define wxUSE_FILE 1 +#define wxUSE_TEXTCTRL 1 +#define wxUSE_CHOICEDLG 1 +#define wxUSE_TOOLTIPS 1 +#endif + +#define WINVER _WIN32_WINNT_WINXP +#define _WIN32_WINNT _WIN32_WINNT_WINXP +#define NTDDI_VERSION NTDDI_WINXP +#define WIN32_LEAN_AND_MEAN + + +#include "wx\wx.h" +#include "wx\notebook.h" +#include +#include +#include +#include +//#include +//#include "wx/checkbox.h" +//#include +//#include +//#include +//#include +//#include +//#include +//#include + +//#include + +#include "../uMod_GlobalDefines.h" +#include "../uMod_Error.h" + + +class uMod_Frame; + +#define MAX_TEXTURES 1024 +enum +{ + ID_Button_Open = wxID_HIGHEST, + ID_Button_Path, + ID_Button_Update, + ID_Button_Reload, + //ID_Button_Save, + //ID_Menu_Pref, + ID_Menu_Exit, + ID_Menu_Lang, + ID_Menu_Help, + ID_Menu_About, + ID_Menu_Acknowledgement, + ID_Menu_StartGame, + ID_Menu_StartGameCMD, + ID_Menu_UseHook, + ID_Menu_AddGame, + ID_Menu_DeleteGame, + ID_Menu_LoadTemplate, + ID_Menu_SaveTemplate, + ID_Menu_SaveTemplateAs, + ID_Menu_SetDefaultTemplate, + ID_Add_Game, + ID_Delete_Game, + ID_Button_Texture, //this entry must be the last!! +}; + +#define ABORT_SERVER L"uMod_Abort_Server" +#define uMod_d3d9_Hook_dll L"uMod_d3d9_HI.dll" +#define uMod_d3d9_DI_dll L"uMod_d3d9_DI.dll" + +#include "uMod_AddTexture.h" +#include "uMod_Settings.h" +#include "uMod_Language.h" +#include "uMod_Event.h" +#include "uMod_Client.h" +#include "uMod_GameInfo.h" +#include "uMod_File.h" +#include "uMod_Sender.h" +#include "uMod_Server.h" +#include "uMod_GamePage.h" +#include "uMod_DirectInjection.h" +#include "uMod_GUI.h" + + +template +int GetMemory(T* &array, int num) +{ + if (array!=(T*)0) delete [] array; + try {array = new T[num];} + catch (...) {array = (T*) 0; return -1;} + return 0; +} + +template +int GetMemory(T* &array, int num, T init) +{ + if (array!=(T*)0) delete [] array; + try {array = new T[num];} + catch (...) {array = (T*) 0; return -1;} + for (int i=0; i +int GetMoreMemory(T* &old_array, int old_num, int new_num) +{ + if (new_num<=old_num) return 0; + T* new_array; + try {new_array = new T[new_num];} + catch (...) {return -1;} + if (old_array!=(T*)0) + { + for (int i=0; i. +*/ + + + +#include "uMod_Main.h" + + +uMod_Sender::uMod_Sender(PipeStruct &pipe) : Pipe(pipe) +{ + OldTextures = NULL; + OldTexturesNum = 0; + try {Buffer = new char[BIG_BUFSIZE];} + catch (...) {Buffer=NULL;} +} + +uMod_Sender::~uMod_Sender(void) +{ + if (Buffer!=NULL) delete [] Buffer; +} + + +int uMod_Sender::Send( const uMod_GameInfo &game, const uMod_GameInfo &game_old, bool force, wxArrayString *comments) +{ + LastError.Empty(); + int key = game.GetKeyBack(); + if (key>=0 && key!=game_old.GetKeyBack()) + { + key = Language->KeyValues[key]; + SendKey( key, CONTROL_KEY_BACK); + } + key = game.GetKeySave(); + if (key>=0 && key!=game_old.GetKeySave()) + { + key = Language->KeyValues[key]; + SendKey( key, CONTROL_KEY_SAVE); + } + key = game.GetKeyNext(); + if (key>=0 && key!=game_old.GetKeyNext()) + { + key = Language->KeyValues[key]; + SendKey( key, CONTROL_KEY_NEXT); + } + + int colour[3], colour_old[3]; + game.GetFontColour( colour); + game_old.GetFontColour( colour_old); + for (int i=0; i<3; i++) if (colour[i]!=colour_old[i]) + { + SendColour( colour, CONTROL_FONT_COLOUR); + break; + } + + game.GetTextureColour( colour); + game_old.GetTextureColour( colour_old); + for (int i=0; i<3; i++) if (colour[i]!=colour_old[i]) + { + SendColour( colour, CONTROL_TEXTURE_COLOUR); + break; + } + + + if ( game.GetSaveSingleTexture() != game_old.GetSaveSingleTexture() ) SendSaveSingleTexture( game.GetSaveSingleTexture()); + if ( game.GetSaveAllTextures() != game_old.GetSaveAllTextures() ) SendSaveAllTextures(game.GetSaveAllTextures()); + + wxString path; + path = game.GetSavePath(); + if (path!=game_old.GetSavePath()) SendPath(path); + + + if (game.GetNumberOfFiles()<=0 && OldTexturesNum==0 && OldTextures==NULL) + { + if (LastError.Len()>0) return 1; + else return 0; + } + + wxArrayString files; + + game.GetFiles( files); + int num = files.GetCount(); + bool *checked = NULL; + if (num>0) + { + if (GetMemory(checked, num)) {LastError << Language->Error_Memory; return -1;} + game.GetChecked( checked, num); + } + + AddTextureClass *tex = NULL;//new AddTextureClass[num+OldTexturesNum]; + if (GetMemory( tex, num+OldTexturesNum)) {LastError << Language->Error_Memory; return -1;} + wxString comment; + + if (force || OldTexturesNum==0 || OldTextures==NULL) + { + //reload everything + for (int i=0; i0 && OldTextures!=NULL) + { + for (int i=0; iError_Memory; return -1;} + for (pos=0; pos looking brute force + for (int i=pos; i0) + { + comments->Empty(); + comments->Alloc(num); + for (int i=0; iAdd(tex[i].Comment); + } + + if (OldTextures!=NULL) delete [] OldTextures; + + OldTexturesNum = num; + OldTextures = tex; + + if (LastError.Len()>0) return 1; + else return 0; +} + + + +int uMod_Sender::SendSaveAllTextures(bool val) +{ + MsgStruct msg; + msg.Control = CONTROL_SAVE_ALL; + if (val) msg.Value = 1; + else msg.Value = 0; + msg.Hash = 0u; + + return SendToGame( (void*) &msg, sizeof(MsgStruct)); +} + +int uMod_Sender::SendSaveSingleTexture(bool val) +{ + MsgStruct msg; + msg.Control = CONTROL_SAVE_SINGLE; + if (val) msg.Value = 1; + else msg.Value = 0; + msg.Hash = 0u; + + return SendToGame( (void*) &msg, sizeof(MsgStruct)); +} + + +int uMod_Sender::SendTextures(unsigned int num, AddTextureClass *tex) +{ + if (Buffer==NULL) return (RETURN_NO_MEMORY); + + MsgStruct *msg; + int pos = 0; + for (unsigned int i=0u; i=BIG_BUFSIZE) //the buffer is full + { + if (int ret = SendToGame( Buffer, pos)) return ret; + pos = 0; + } + + msg = (MsgStruct*) &Buffer[pos]; + msg->Hash = temp_hash; + msg->Value = size; + pos += sizeof(MsgStruct); + + if (tex[i].Add) + { + msg->Control = CONTROL_FORCE_RELOAD_TEXTURE_DATA; //we always force because whether force is true or not + //if (Add==true && WasAdded[j]!=true) the texture is loaded the first time, or in previous loads it could not be loaded + //because an other texture was send with the same hash, in all cases forcing is the best choice (atm) + char* temp = tex[i].Textures[j]; + if (temp!=NULL) + { + unsigned int l = 0u; + while (lControl = CONTROL_REMOVE_TEXTURE; + tex[i].WasAdded[j] = false; + } + } + else if (tex[i].Add && tex[i].WasAdded[j]) // this texture could be removed, due to a rearranging of the list + { + bool hit = false; //we send only if this has was not send before + unsigned long temp_hash = tex[i].Hash[j]; + for (unsigned int ii=0u; ii=BIG_BUFSIZE) //the buffer is full + { + if (int ret = SendToGame( Buffer, pos)) return ret; + pos = 0; + } + + msg = (MsgStruct*) &Buffer[pos]; + msg->Control = CONTROL_END_TEXTURES; //End of texture sending + msg->Hash = 0u; + msg->Value = 0; + pos += sizeof(MsgStruct); + if (int ret = SendToGame( Buffer, pos)) return ret; + + if (LastError.Len()>0) return 1; + else return 0; +} + + +int uMod_Sender::SendKey(int key, int ctr) +{ + MsgStruct msg; + msg.Control = ctr; + msg.Value = key; + msg.Hash = 0u; + + return SendToGame( (void*) &msg, sizeof(MsgStruct)); +} + +#define D3DCOLOR_ARGB(a,r,g,b) ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff))) + +int uMod_Sender::SendColour( int* colour, int ctr) +{ + MsgStruct msg; + msg.Control = ctr; + msg.Value = D3DCOLOR_ARGB( 255, colour[0], colour[1], colour[2]); + msg.Hash = 0u; + + return SendToGame( (void*) &msg, sizeof(MsgStruct)); +} +#undef D3DCOLOR_ARGB + + +int uMod_Sender::SendPath( const wxString &path) +{ + MsgStruct *msg = (MsgStruct*) Buffer; + + msg->Hash = 0u; + msg->Control = CONTROL_SET_DIR; + + const wchar_t *file = path.wc_str(); + wchar_t *buff_file = (wchar_t*) &Buffer[sizeof(MsgStruct)]; + int len = 0; + while (file[len] && (sizeof(MsgStruct)+len*sizeof(wchar_t))Value = len*sizeof(wchar_t); + return SendToGame( Buffer, sizeof(MsgStruct)+len*sizeof(wchar_t)); +} + + +int uMod_Sender::SendToGame( void *msg, unsigned long len) +{ + if (len==0) return (RETURN_BAD_ARGUMENT); + unsigned long num; + + if (Pipe.Out==INVALID_HANDLE_VALUE) {LastError << Language->Error_NoPipe; return -1;} + bool ret = WriteFile( Pipe.Out, (const void*) msg, len, &num, NULL); + if (!ret || len!=num) {LastError << Language->Error_WritePipe; return -1;} + if (!FlushFileBuffers(Pipe.Out)) {LastError << Language->Error_FlushPipe; return -1;} + return 0; +} + diff --git a/uMod2/uMod_GUI/uMod_Sender.h b/uMod2/uMod_GUI/uMod_Sender.h new file mode 100644 index 0000000..336b194 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Sender.h @@ -0,0 +1,63 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_SENDER_H_ +#define uMod_SENDER_H_ + +#include "uMod_Main.h" + + +// an object of this class is owned by each uMod_GamePage object. It act as sender ^^ +class uMod_Sender +{ +public: + uMod_Sender(PipeStruct &pipe); + ~uMod_Sender(void); + + int Send( const uMod_GameInfo &game, const uMod_GameInfo &game_old, bool force=false, wxArrayString *comments=NULL); + + wxString LastError; + +private: + int SendSaveAllTextures(bool val); + int SendSaveSingleTexture(bool val); + + int SendTextures(unsigned int num, AddTextureClass *tex); + + int SendKey(int key, int ctr); + + int SendPath( const wxString &path); + + int SendColour( int* colour, int ctr); + + char *Buffer; + int SendToGame( void* msg, unsigned long len); + + int AddFile( AddTextureClass *tex, wxString file, bool add, bool force); + int AddZip( AddTextureClass *tex, wxString file, bool add, bool force, bool tpf); + int AddContent( char* buffer, unsigned int len, const char* pw, AddTextureClass *tex, bool add, bool force); + + PipeStruct &Pipe; + AddTextureClass *OldTextures; + int OldTexturesNum; +}; + + +#endif /* uMod_SENDER_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Server.cpp b/uMod2/uMod_GUI/uMod_Server.cpp new file mode 100644 index 0000000..6aacf63 --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Server.cpp @@ -0,0 +1,132 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + +uMod_Server::uMod_Server(uMod_Frame *frame) : wxThread(wxTHREAD_JOINABLE) +{ + MainFrame = frame; +} + + +uMod_Server::~uMod_Server(void) +{ +} + + +void* uMod_Server::Entry(void) +{ + bool fConnected = false; + HANDLE pipe_in; + HANDLE pipe_out; + char buffer[SMALL_BUFSIZE]; + wxString abort = ABORT_SERVER; + + while(1) + { +/* + Beep(300,100); + Beep(600,100); +*/ + pipe_in = CreateNamedPipeW( + PIPE_Game2uMod, // pipe name + PIPE_ACCESS_INBOUND, // read access + PIPE_TYPE_BYTE | // byte type pipe + PIPE_WAIT, // blocking mode + PIPE_UNLIMITED_INSTANCES, // max. instances + SMALL_BUFSIZE, // output buffer size + SMALL_BUFSIZE, // input buffer size + 0, // client time-out + NULL); // default security attribute + if (pipe_in == INVALID_HANDLE_VALUE) return NULL; + + pipe_out = CreateNamedPipeW( + PIPE_uMod2Game, // pipe name + PIPE_ACCESS_OUTBOUND, // write access + PIPE_TYPE_BYTE | // byte type pipe + PIPE_WAIT, // blocking mode + PIPE_UNLIMITED_INSTANCES, // max. instances + BIG_BUFSIZE, // output buffer size + BIG_BUFSIZE, // input buffer size + 0, // client time-out + NULL); // default security attribute + if (pipe_out == INVALID_HANDLE_VALUE) return NULL; + + + // at first connect to the incoming pipe !!! + fConnected = ConnectNamedPipe(pipe_in, NULL) ? + true : (GetLastError() == ERROR_PIPE_CONNECTED); + /* + Beep(900,100); + Beep(600,100); + Beep(300,100); + */ + if (fConnected) + { + unsigned long num = 0; + //read the name of the game + bool fSuccess = ReadFile( + pipe_in, // handle to pipe + buffer, // buffer to receive data + SMALL_BUFSIZE, // size of buffer + &num, // number of bytes read + NULL); // not overlapped I/O + + if (fSuccess) + { + if (num>2) + { + buffer[num]=0; + buffer[num-1]=0; + wxString name = (wchar_t*) buffer; + + if (name==abort) // kill this server thread + { + //Beep(1200,300); + CloseHandle(pipe_in); + return NULL; + } + + + fConnected = ConnectNamedPipe(pipe_out, NULL) ? + true : (GetLastError() == ERROR_PIPE_CONNECTED); + if (fConnected) + { + uMod_Event event( uMod_EVENT_TYPE, ID_Add_Game); + event.SetName(name); + event.SetPipeIn(pipe_in); + event.SetPipeOut(pipe_out); + wxPostEvent( MainFrame, event); + } + else + { + CloseHandle(pipe_in); + CloseHandle(pipe_out); + return NULL; + } + } + } + } + else CloseHandle(pipe_in); + } + return NULL; +} + diff --git a/uMod2/uMod_GUI/uMod_Server.h b/uMod2/uMod_GUI/uMod_Server.h new file mode 100644 index 0000000..a651d2f --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Server.h @@ -0,0 +1,45 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#ifndef uMod_SERVER_H_ +#define uMod_SERVER_H_ +#include "uMod_Main.h" + +// an object of this class should be created only once +// it waits for incomming connections (a starting game) +// and if so, it send a message to the mainthread + +// Note the server thread can only be killed, if one connect to it and send "uMod_ABORT" as game name +class uMod_Server : public wxThread +{ +public: + uMod_Server(uMod_Frame *frame); + virtual ~uMod_Server(void); + + + void* Entry(void); + +private: + + uMod_Frame *MainFrame; +}; + + +#endif /* uMod_SERVER_H_ */ diff --git a/uMod2/uMod_GUI/uMod_Settings.cpp b/uMod2/uMod_GUI/uMod_Settings.cpp new file mode 100644 index 0000000..f37a26e --- /dev/null +++ b/uMod2/uMod_GUI/uMod_Settings.cpp @@ -0,0 +1,157 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + + + +#include "uMod_Main.h" + + +uMod_Settings::uMod_Settings(void) +{ + XSize = 600; + YSize = 400; + XPos = -1; + YPos = -1; + UseHook = false; + Language = "English"; +} + +uMod_Settings::uMod_Settings(uMod_Settings &set) +{ + XSize = set.XSize; + YSize = set.YSize; + XPos = set.XPos; + YPos = set.YPos; + UseHook = set.UseHook; + Language = set.Language; +} + + +#define SETTINGS_FILE "uMod_Settings.txt" + +int uMod_Settings::Load(void) +{ + wxFile file; + + if (!file.Access(SETTINGS_FILE, wxFile::read)) {return -1;} + file.Open(SETTINGS_FILE, wxFile::read); + if (!file.IsOpened()) return -1; + + unsigned len = file.Length(); + + unsigned char* buffer; + try {buffer = new unsigned char [len+2];} + catch (...) {return -1;} + + unsigned int result = file.Read( buffer, len); + file.Close(); + + if (result != len) {delete [] buffer; return -1;} + + wchar_t *buff = (wchar_t*)buffer; + len/=2; + buff[len]=0; + + wxString content; + content = buff; + delete [] buffer; + + wxStringTokenizer token( content, "\n"); + + int num = token.CountTokens(); + wxString line; + wxString command; + wxString value; + + UseHook = false; + for (int i=0; i. +*/ + + +#ifndef uMod_SETTINGS_H_ +#define uMod_SETTINGS_H_ + + +#include "uMod_Main.h" + +class uMod_Settings +{ +public: + uMod_Settings(void); + uMod_Settings(uMod_Settings &set); + + + int XSize, YSize; + int XPos, YPos; + bool UseHook; + wxString Language; + + int Load(void); + int Save(void); + +}; + + +#endif /* uMod_SETTINGS_H_ */ diff --git a/uMod2/uMod_GUI/unzip.cpp b/uMod2/uMod_GUI/unzip.cpp new file mode 100644 index 0000000..77c330a --- /dev/null +++ b/uMod2/uMod_GUI/unzip.cpp @@ -0,0 +1,4165 @@ +#define UNICODE /*added by ROTA*/ +#include +#include +#include +#include +//#include /*added by ROTA*/ +#include +#include "unzip.h" + +// THIS FILE is almost entirely based upon code by Jean-loup Gailly +// and Mark Adler. It has been modified by Lucian Wischik. +// The modifications were: incorporate the bugfixes of 1.1.4, allow +// unzipping to/from handles/pipes/files/memory, encryption, unicode, +// a windowsish api, and putting everything into a single .cpp file. +// The original code may be found at http://www.gzip.org/zlib/ +// The original copyright text follows. +// +// +// +// zlib.h -- interface of the 'zlib' general purpose compression library +// version 1.1.3, July 9th, 1998 +// +// Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// +// Jean-loup Gailly Mark Adler +// jloup@gzip.org madler@alumni.caltech.edu +// +// +// The data format used by the zlib library is described by RFCs (Request for +// Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt +// (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +// +// +// The 'zlib' compression library provides in-memory compression and +// decompression functions, including integrity checks of the uncompressed +// data. This version of the library supports only one compression method +// (deflation) but other algorithms will be added later and will have the same +// stream interface. +// +// Compression can be done in a single step if the buffers are large +// enough (for example if an input file is mmap'ed), or can be done by +// repeated calls of the compression function. In the latter case, the +// application must provide more input and/or consume the output +// (providing more output space) before each call. +// +// The library also supports reading and writing files in gzip (.gz) format +// with an interface similar to that of stdio. +// +// The library does not install any signal handler. The decoder checks +// the consistency of the compressed data, so the library should never +// crash even in case of corrupted input. +// +// for more info about .ZIP format, see ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip +// PkWare has also a specification at ftp://ftp.pkware.com/probdesc.zip + +#define ZIP_HANDLE 1 +#define ZIP_FILENAME 2 +#define ZIP_MEMORY 3 + + +#define zmalloc(len) malloc(len) + +#define zfree(p) free(p) + +/* +void *zmalloc(unsigned int len) +{ char *buf = new char[len+32]; + for (int i=0; i<16; i++) + { buf[i]=i; + buf[len+31-i]=i; + } + *((unsigned int*)buf) = len; + char c[1000]; wsprintf(c,"malloc 0x%lx - %lu",buf+16,len); + OutputDebugString(c); + return buf+16; +} + +void zfree(void *buf) +{ char c[1000]; wsprintf(c,"free 0x%lx",buf); + OutputDebugString(c); + char *p = ((char*)buf)-16; + unsigned int len = *((unsigned int*)p); + bool blown=false; + for (int i=0; i<16; i++) + { char lo = p[i]; + char hi = p[len+31-i]; + if (hi!=i || (lo!=i && i>4)) blown=true; + } + if (blown) + { OutputDebugString("BLOWN!!!"); + } + delete[] p; +} +*/ + + +typedef struct tm_unz_s +{ unsigned int tm_sec; // seconds after the minute - [0,59] + unsigned int tm_min; // minutes after the hour - [0,59] + unsigned int tm_hour; // hours since midnight - [0,23] + unsigned int tm_mday; // day of the month - [1,31] + unsigned int tm_mon; // months since January - [0,11] + unsigned int tm_year; // years - [1980..2044] +} tm_unz; + + +// unz_global_info structure contain global data about the ZIPfile +typedef struct unz_global_info_s +{ unsigned long number_entry; // total number of entries in the central dir on this disk + unsigned long size_comment; // size of the global comment of the zipfile +} unz_global_info; + +// unz_file_info contain information about a file in the zipfile +typedef struct unz_file_info_s +{ unsigned long version; // version made by 2 bytes + unsigned long version_needed; // version needed to extract 2 bytes + unsigned long flag; // general purpose bit flag 2 bytes + unsigned long compression_method; // compression method 2 bytes + unsigned long dosDate; // last mod file date in Dos fmt 4 bytes + unsigned long crc; // crc-32 4 bytes + unsigned long compressed_size; // compressed size 4 bytes + unsigned long uncompressed_size; // uncompressed size 4 bytes + unsigned long size_filename; // filename length 2 bytes + unsigned long size_file_extra; // extra field length 2 bytes + unsigned long size_file_comment; // file comment length 2 bytes + unsigned long disk_num_start; // disk number start 2 bytes + unsigned long internal_fa; // internal file attributes 2 bytes + unsigned long external_fa; // external file attributes 4 bytes + tm_unz tmu_date; +} unz_file_info; + + +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) +#define UNZ_PASSWORD (-106) + + + + + + + +#define ZLIB_VERSION "1.1.3" + + +// Allowed flush values; see deflate() for details +#define Z_NO_FLUSH 0 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 + + +// compression levels +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) + +// compression strategy; see deflateInit2() for details +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_DEFAULT_STRATEGY 0 + +// Possible values of the data_type field +#define Z_BINARY 0 +#define Z_ASCII 1 +#define Z_UNKNOWN 2 + +// The deflate compression method (the only one supported in this version) +#define Z_DEFLATED 8 + +// for initializing zalloc, zfree, opaque +#define Z_NULL 0 + +// case sensitivity when searching for filenames +#define CASE_SENSITIVE 1 +#define CASE_INSENSITIVE 2 + + +// Return codes for the compression/decompression functions. Negative +// values are errors, positive values are used for special but normal events. +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) + + + +// Basic data types +typedef unsigned char Byte; // 8 bits +typedef unsigned int uInt; // 16 bits or more +typedef unsigned long uLong; // 32 bits or more +typedef void *voidpf; +typedef void *voidp; +typedef long z_off_t; + + + + + + + + + + + + +typedef voidpf (*alloc_func) (voidpf opaque, uInt items, uInt size); +typedef void (*free_func) (voidpf opaque, voidpf address); + +struct internal_state; + +typedef struct z_stream_s { + Byte *next_in; // next input byte + uInt avail_in; // number of bytes available at next_in + uLong total_in; // total nb of input bytes read so far + + Byte *next_out; // next output byte should be put there + uInt avail_out; // remaining free space at next_out + uLong total_out; // total nb of bytes output so far + + char *msg; // last error message, NULL if no error + struct internal_state *state; // not visible by applications + + alloc_func zalloc; // used to allocate the internal state + free_func zfree; // used to free the internal state + voidpf opaque; // private data object passed to zalloc and zfree + + int data_type; // best guess about the data type: ascii or binary + uLong adler; // adler32 value of the uncompressed data + uLong reserved; // reserved for future use +} z_stream; + +typedef z_stream *z_streamp; + + +// The application must update next_in and avail_in when avail_in has +// dropped to zero. It must update next_out and avail_out when avail_out +// has dropped to zero. The application must initialize zalloc, zfree and +// opaque before calling the init function. All other fields are set by the +// compression library and must not be updated by the application. +// +// The opaque value provided by the application will be passed as the first +// parameter for calls of zalloc and zfree. This can be useful for custom +// memory management. The compression library attaches no meaning to the +// opaque value. +// +// zalloc must return Z_NULL if there is not enough memory for the object. +// If zlib is used in a multi-threaded application, zalloc and zfree must be +// thread safe. +// +// The fields total_in and total_out can be used for statistics or +// progress reports. After compression, total_in holds the total size of +// the uncompressed data and may be saved for use in the decompressor +// (particularly if the decompressor wants to decompress everything in +// a single step). +// + + +// basic functions + +const char *zlibVersion (); +// The application can compare zlibVersion and ZLIB_VERSION for consistency. +// If the first character differs, the library code actually used is +// not compatible with the zlib.h header file used by the application. +// This check is automatically made by inflateInit. + + + + + + +int inflate (z_streamp strm, int flush); +// +// inflate decompresses as much data as possible, and stops when the input +// buffer becomes empty or the output buffer becomes full. It may some +// introduce some output latency (reading input without producing any output) +// except when forced to flush. +// +// The detailed semantics are as follows. inflate performs one or both of the +// following actions: +// +// - Decompress more input starting at next_in and update next_in and avail_in +// accordingly. If not all input can be processed (because there is not +// enough room in the output buffer), next_in is updated and processing +// will resume at this point for the next call of inflate(). +// +// - Provide more output starting at next_out and update next_out and avail_out +// accordingly. inflate() provides as much output as possible, until there +// is no more input data or no more space in the output buffer (see below +// about the flush parameter). +// +// Before the call of inflate(), the application should ensure that at least +// one of the actions is possible, by providing more input and/or consuming +// more output, and updating the next_* and avail_* values accordingly. +// The application can consume the uncompressed output when it wants, for +// example when the output buffer is full (avail_out == 0), or after each +// call of inflate(). If inflate returns Z_OK and with zero avail_out, it +// must be called again after making room in the output buffer because there +// might be more output pending. +// +// If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much +// output as possible to the output buffer. The flushing behavior of inflate is +// not specified for values of the flush parameter other than Z_SYNC_FLUSH +// and Z_FINISH, but the current implementation actually flushes as much output +// as possible anyway. +// +// inflate() should normally be called until it returns Z_STREAM_END or an +// error. However if all decompression is to be performed in a single step +// (a single call of inflate), the parameter flush should be set to +// Z_FINISH. In this case all pending input is processed and all pending +// output is flushed; avail_out must be large enough to hold all the +// uncompressed data. (The size of the uncompressed data may have been saved +// by the compressor for this purpose.) The next operation on this stream must +// be inflateEnd to deallocate the decompression state. The use of Z_FINISH +// is never required, but can be used to inform inflate that a faster routine +// may be used for the single inflate() call. +// +// If a preset dictionary is needed at this point (see inflateSetDictionary +// below), inflate sets strm-adler to the adler32 checksum of the +// dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise +// it sets strm->adler to the adler32 checksum of all output produced +// so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or +// an error code as described below. At the end of the stream, inflate() +// checks that its computed adler32 checksum is equal to that saved by the +// compressor and returns Z_STREAM_END only if the checksum is correct. +// +// inflate() returns Z_OK if some progress has been made (more input processed +// or more output produced), Z_STREAM_END if the end of the compressed data has +// been reached and all uncompressed output has been produced, Z_NEED_DICT if a +// preset dictionary is needed at this point, Z_DATA_ERROR if the input data was +// corrupted (input stream not conforming to the zlib format or incorrect +// adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent +// (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not +// enough memory, Z_BUF_ERROR if no progress is possible or if there was not +// enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR +// case, the application may then call inflateSync to look for a good +// compression block. +// + + +int inflateEnd (z_streamp strm); +// +// All dynamically allocated data structures for this stream are freed. +// This function discards any unprocessed input and does not flush any +// pending output. +// +// inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state +// was inconsistent. In the error case, msg may be set but then points to a +// static string (which must not be deallocated). + + // Advanced functions + +// The following functions are needed only in some special applications. + + + + + +int inflateSetDictionary (z_streamp strm, + const Byte *dictionary, + uInt dictLength); +// +// Initializes the decompression dictionary from the given uncompressed byte +// sequence. This function must be called immediately after a call of inflate +// if this call returned Z_NEED_DICT. The dictionary chosen by the compressor +// can be determined from the Adler32 value returned by this call of +// inflate. The compressor and decompressor must use exactly the same +// dictionary. +// +// inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a +// parameter is invalid (such as NULL dictionary) or the stream state is +// inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the +// expected one (incorrect Adler32 value). inflateSetDictionary does not +// perform any decompression: this will be done by subsequent calls of +// inflate(). + + +int inflateSync (z_streamp strm); +// +// Skips invalid compressed data until a full flush point can be found, or until all +// available input is skipped. No output is provided. +// +// inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR +// if no more input was provided, Z_DATA_ERROR if no flush point has been found, +// or Z_STREAM_ERROR if the stream structure was inconsistent. In the success +// case, the application may save the current current value of total_in which +// indicates where valid compressed data was found. In the error case, the +// application may repeatedly call inflateSync, providing more input each time, +// until success or end of the input data. + + +int inflateReset (z_streamp strm); +// This function is equivalent to inflateEnd followed by inflateInit, +// but does not free and reallocate all the internal decompression state. +// The stream will keep attributes that may have been set by inflateInit2. +// +// inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source +// stream state was inconsistent (such as zalloc or state being NULL). +// + + + +// checksum functions +// These functions are not related to compression but are exported +// anyway because they might be useful in applications using the +// compression library. + +uLong adler32 (uLong adler, const Byte *buf, uInt len); +// Update a running Adler-32 checksum with the bytes buf[0..len-1] and +// return the updated checksum. If buf is NULL, this function returns +// the required initial value for the checksum. +// An Adler-32 checksum is almost as reliable as a CRC32 but can be computed +// much faster. Usage example: +// +// uLong adler = adler32(0L, Z_NULL, 0); +// +// while (read_buffer(buffer, length) != EOF) { +// adler = adler32(adler, buffer, length); +// } +// if (adler != original_adler) error(); + +uLong ucrc32 (uLong crc, const Byte *buf, uInt len); +// Update a running crc with the bytes buf[0..len-1] and return the updated +// crc. If buf is NULL, this function returns the required initial value +// for the crc. Pre- and post-conditioning (one's complement) is performed +// within this function so it shouldn't be done by the application. +// Usage example: +// +// uLong crc = crc32(0L, Z_NULL, 0); +// +// while (read_buffer(buffer, length) != EOF) { +// crc = crc32(crc, buffer, length); +// } +// if (crc != original_crc) error(); + + + + +const char *zError (int err); +int inflateSyncPoint (z_streamp z); +const uLong *get_crc_table (void); + + + +typedef unsigned char uch; +typedef uch uchf; +typedef unsigned short ush; +typedef ush ushf; +typedef unsigned long ulg; + + + +const char * const z_errmsg[10] = { // indexed by 2-zlib_error +"need dictionary", // Z_NEED_DICT 2 +"stream end", // Z_STREAM_END 1 +"", // Z_OK 0 +"file error", // Z_ERRNO (-1) +"stream error", // Z_STREAM_ERROR (-2) +"data error", // Z_DATA_ERROR (-3) +"insufficient memory", // Z_MEM_ERROR (-4) +"buffer error", // Z_BUF_ERROR (-5) +"incompatible version",// Z_VERSION_ERROR (-6) +""}; + + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +// To be used only when the state is known to be valid + + // common constants + + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +// The three kinds of block type + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +// The minimum and maximum match lengths + +#define PRESET_DICT 0x20 // preset dictionary flag in zlib header + + // target dependencies + +#define OS_CODE 0x0b // Window 95 & Windows NT + + + + // functions + +#define zmemzero(dest, len) memset(dest, 0, len) + +// Diagnostic functions +#define LuAssert(cond,msg) +#define LuTrace(x) +#define LuTracev(x) +#define LuTracevv(x) +#define LuTracec(c,x) +#define LuTracecv(c,x) + + +typedef uLong (*check_func) (uLong check, const Byte *buf, uInt len); +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size); +void zcfree (voidpf opaque, voidpf ptr); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) + +//void ZFREE(z_streamp strm,voidpf addr) +//{ *((strm)->zfree))((strm)->opaque, addr); +//} + +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + + + + +// Huffman code lookup table entry--this entry is four bytes for machines +// that have 16-bit pointers (e.g. PC's in the small or medium model). + + +typedef struct inflate_huft_s inflate_huft; + +struct inflate_huft_s { + union { + struct { + Byte Exop; // number of extra bits or operation + Byte Bits; // number of bits in this code or subcode + } what; + uInt pad; // pad structure to a power of 2 (4 bytes for + } word; // 16-bit, 8 bytes for 32-bit int's) + uInt base; // literal, length base, distance base, or table offset +}; + +// Maximum size of dynamic tree. The maximum found in a long but non- +// exhaustive search was 1004 huft structures (850 for length/literals +// and 154 for distances, the latter actually the result of an +// exhaustive search). The actual maximum is not known, but the +// value below is more than safe. +#define MANY 1440 + +int inflate_trees_bits ( + uInt *, // 19 code lengths + uInt *, // bits tree desired/actual depth + inflate_huft * *, // bits tree result + inflate_huft *, // space for trees + z_streamp); // for messages + +int inflate_trees_dynamic ( + uInt, // number of literal/length codes + uInt, // number of distance codes + uInt *, // that many (total) code lengths + uInt *, // literal desired/actual bit depth + uInt *, // distance desired/actual bit depth + inflate_huft * *, // literal/length tree result + inflate_huft * *, // distance tree result + inflate_huft *, // space for trees + z_streamp); // for messages + +int inflate_trees_fixed ( + uInt *, // literal desired/actual bit depth + uInt *, // distance desired/actual bit depth + const inflate_huft * *, // literal/length tree result + const inflate_huft * *, // distance tree result + z_streamp); // for memory allocation + + + + + +struct inflate_blocks_state; +typedef struct inflate_blocks_state inflate_blocks_statef; + +inflate_blocks_statef * inflate_blocks_new ( + z_streamp z, + check_func c, // check function + uInt w); // window size + +int inflate_blocks ( + inflate_blocks_statef *, + z_streamp , + int); // initial return code + +void inflate_blocks_reset ( + inflate_blocks_statef *, + z_streamp , + uLong *); // check value on output + +int inflate_blocks_free ( + inflate_blocks_statef *, + z_streamp); + +void inflate_set_dictionary ( + inflate_blocks_statef *s, + const Byte *d, // dictionary + uInt n); // dictionary length + +int inflate_blocks_sync_point ( + inflate_blocks_statef *s); + + + + +struct inflate_codes_state; +typedef struct inflate_codes_state inflate_codes_statef; + +inflate_codes_statef *inflate_codes_new ( + uInt, uInt, + const inflate_huft *, const inflate_huft *, + z_streamp ); + +int inflate_codes ( + inflate_blocks_statef *, + z_streamp , + int); + +void inflate_codes_free ( + inflate_codes_statef *, + z_streamp ); + + + + +typedef enum { + IBM_TYPE, // get type bits (3, including end bit) + IBM_LENS, // get lengths for stored + IBM_STORED, // processing stored block + IBM_TABLE, // get table lengths + IBM_BTREE, // get bit lengths tree for a dynamic block + IBM_DTREE, // get length, distance trees for a dynamic block + IBM_CODES, // processing fixed or dynamic block + IBM_DRY, // output remaining window bytes + IBM_DONE, // finished last block, done + IBM_BAD} // got a data error--stuck here +inflate_block_mode; + +// inflate blocks semi-private state +struct inflate_blocks_state { + + // mode + inflate_block_mode mode; // current inflate_block mode + + // mode dependent information + union { + uInt left; // if STORED, bytes left to copy + struct { + uInt table; // table lengths (14 bits) + uInt index; // index into blens (or border) + uInt *blens; // bit lengths of codes + uInt bb; // bit length tree depth + inflate_huft *tb; // bit length decoding tree + } trees; // if DTREE, decoding info for trees + struct { + inflate_codes_statef + *codes; + } decode; // if CODES, current state + } sub; // submode + uInt last; // true if this block is the last block + + // mode independent information + uInt bitk; // bits in bit buffer + uLong bitb; // bit buffer + inflate_huft *hufts; // single malloc for tree space + Byte *window; // sliding window + Byte *end; // one byte after sliding window + Byte *read; // window read pointer + Byte *write; // window write pointer + check_func checkfn; // check function + uLong check; // check on output + +}; + + +// defines for inflate input/output +// update pointers and return +#define UPDBITS {s->bitb=b;s->bitk=k;} +#define UPDIN {z->avail_in=n;z->total_in+=(uLong)(p-z->next_in);z->next_in=p;} +#define UPDOUT {s->write=q;} +#define UPDATE {UPDBITS UPDIN UPDOUT} +#define LEAVE {UPDATE return inflate_flush(s,z,r);} +// get bytes and bits +#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;} +#define NEEDBYTE {if(n)r=Z_OK;else LEAVE} +#define NEXTBYTE (n--,*p++) +#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<>=(j);k-=(j);} +// output bytes +#define WAVAIL (uInt)(qread?s->read-q-1:s->end-q) +#define LOADOUT {q=s->write;m=(uInt)WAVAIL;m;} +#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}} +#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT} +#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;} +#define OUTBYTE(a) {*q++=(Byte)(a);m--;} +// load local pointers +#define LOAD {LOADIN LOADOUT} + +// masks for lower bits (size given to avoid silly warnings with Visual C++) +// And'ing with mask[n] masks the lower n bits +const uInt inflate_mask[17] = { + 0x0000, + 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, + 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff +}; + +// copy as much as possible from the sliding window to the output area +int inflate_flush (inflate_blocks_statef *, z_streamp, int); + +int inflate_fast (uInt, uInt, const inflate_huft *, const inflate_huft *, inflate_blocks_statef *, z_streamp ); + + + +const uInt fixed_bl = 9; +const uInt fixed_bd = 5; +const inflate_huft fixed_tl[] = { + {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, + {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192}, + {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160}, + {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224}, + {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144}, + {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208}, + {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176}, + {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240}, + {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, + {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200}, + {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168}, + {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232}, + {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152}, + {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216}, + {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184}, + {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248}, + {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, + {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196}, + {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164}, + {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228}, + {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148}, + {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212}, + {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180}, + {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244}, + {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204}, + {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172}, + {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236}, + {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156}, + {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220}, + {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188}, + {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252}, + {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, + {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194}, + {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162}, + {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226}, + {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146}, + {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210}, + {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178}, + {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242}, + {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, + {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202}, + {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170}, + {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234}, + {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154}, + {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218}, + {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186}, + {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250}, + {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, + {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198}, + {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166}, + {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230}, + {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150}, + {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214}, + {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182}, + {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246}, + {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206}, + {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174}, + {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238}, + {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158}, + {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222}, + {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190}, + {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254}, + {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, + {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193}, + {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161}, + {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225}, + {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145}, + {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209}, + {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177}, + {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241}, + {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, + {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201}, + {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169}, + {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233}, + {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153}, + {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217}, + {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185}, + {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249}, + {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, + {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197}, + {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165}, + {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229}, + {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149}, + {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213}, + {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181}, + {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245}, + {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205}, + {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173}, + {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237}, + {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157}, + {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221}, + {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189}, + {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253}, + {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, + {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195}, + {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163}, + {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227}, + {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147}, + {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211}, + {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179}, + {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243}, + {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, + {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203}, + {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171}, + {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235}, + {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155}, + {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219}, + {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187}, + {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251}, + {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, + {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199}, + {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167}, + {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231}, + {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151}, + {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215}, + {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183}, + {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247}, + {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207}, + {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175}, + {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239}, + {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159}, + {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223}, + {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191}, + {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255} + }; +const inflate_huft fixed_td[] = { + {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097}, + {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385}, + {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193}, + {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577}, + {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145}, + {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577}, + {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289}, + {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577} + }; + + + + + + + +// copy as much as possible from the sliding window to the output area +int inflate_flush(inflate_blocks_statef *s,z_streamp z,int r) +{ + uInt n; + Byte *p; + Byte *q; + + // local copies of source and destination pointers + p = z->next_out; + q = s->read; + + // compute number of bytes to copy as far as end of window + n = (uInt)((q <= s->write ? s->write : s->end) - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + // update counters + z->avail_out -= n; + z->total_out += n; + + // update check information + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + // copy as far as end of window + if (n!=0) // check for n!=0 to avoid waking up CodeGuard + { memcpy(p, q, n); + p += n; + q += n; + } + + // see if more to copy at beginning of window + if (q == s->end) + { + // wrap pointers + q = s->window; + if (s->write == s->end) + s->write = s->window; + + // compute bytes to copy + n = (uInt)(s->write - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + // update counters + z->avail_out -= n; + z->total_out += n; + + // update check information + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + // copy + if (n!=0) {memcpy(p,q,n); p+=n; q+=n;} + } + + // update pointers + z->next_out = p; + s->read = q; + + // done + return r; +} + + + + + + +// simplify the use of the inflate_huft type with some defines +#define exop word.what.Exop +#define bits word.what.Bits + +typedef enum { // waiting for "i:"=input, "o:"=output, "x:"=nothing + START, // x: set up for LEN + LEN, // i: get length/literal/eob next + LENEXT, // i: getting length extra (have base) + DIST, // i: get distance next + DISTEXT, // i: getting distance extra + COPY, // o: copying bytes in window, waiting for space + LIT, // o: got literal, waiting for output space + WASH, // o: got eob, possibly still output waiting + END, // x: got eob and all data flushed + BADCODE} // x: got error +inflate_codes_mode; + +// inflate codes private state +struct inflate_codes_state { + + // mode + inflate_codes_mode mode; // current inflate_codes mode + + // mode dependent information + uInt len; + union { + struct { + const inflate_huft *tree; // pointer into tree + uInt need; // bits needed + } code; // if LEN or DIST, where in tree + uInt lit; // if LIT, literal + struct { + uInt get; // bits to get for extra + uInt dist; // distance back to copy from + } copy; // if EXT or COPY, where and how much + } sub; // submode + + // mode independent information + Byte lbits; // ltree bits decoded per branch + Byte dbits; // dtree bits decoder per branch + const inflate_huft *ltree; // literal/length/eob tree + const inflate_huft *dtree; // distance tree + +}; + + +inflate_codes_statef *inflate_codes_new( +uInt bl, uInt bd, +const inflate_huft *tl, +const inflate_huft *td, // need separate declaration for Borland C++ +z_streamp z) +{ + inflate_codes_statef *c; + + if ((c = (inflate_codes_statef *) + ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL) + { + c->mode = START; + c->lbits = (Byte)bl; + c->dbits = (Byte)bd; + c->ltree = tl; + c->dtree = td; + LuTracev((stderr, "inflate: codes new\n")); + } + return c; +} + + +int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r) +{ + uInt j; // temporary storage + const inflate_huft *t; // temporary pointer + uInt e; // extra bits or operation + uLong b; // bit buffer + uInt k; // bits in bit buffer + Byte *p; // input data pointer + uInt n; // bytes available there + Byte *q; // output window write pointer + uInt m; // bytes to end of window or read pointer + Byte *f; // pointer to copy strings from + inflate_codes_statef *c = s->sub.decode.codes; // codes state + + // copy input/output information to locals (UPDATE macro restores) + LOAD + + // process input and output based on current state + for(;;) switch (c->mode) + { // waiting for "i:"=input, "o:"=output, "x:"=nothing + case START: // x: set up for LEN +#ifndef SLOW + if (m >= 258 && n >= 10) + { + UPDATE + r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z); + LOAD + if (r != Z_OK) + { + c->mode = r == Z_STREAM_END ? WASH : BADCODE; + break; + } + } +#endif // !SLOW + c->sub.code.need = c->lbits; + c->sub.code.tree = c->ltree; + c->mode = LEN; + case LEN: // i: get length/literal/eob next + j = c->sub.code.need; + NEEDBITS(j) + t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); + DUMPBITS(t->bits) + e = (uInt)(t->exop); + if (e == 0) // literal + { + c->sub.lit = t->base; + LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", t->base)); + c->mode = LIT; + break; + } + if (e & 16) // length + { + c->sub.copy.get = e & 15; + c->len = t->base; + c->mode = LENEXT; + break; + } + if ((e & 64) == 0) // next table + { + c->sub.code.need = e; + c->sub.code.tree = t + t->base; + break; + } + if (e & 32) // end of block + { + LuTracevv((stderr, "inflate: end of block\n")); + c->mode = WASH; + break; + } + c->mode = BADCODE; // invalid code + z->msg = (char*)"invalid literal/length code"; + r = Z_DATA_ERROR; + LEAVE + case LENEXT: // i: getting length extra (have base) + j = c->sub.copy.get; + NEEDBITS(j) + c->len += (uInt)b & inflate_mask[j]; + DUMPBITS(j) + c->sub.code.need = c->dbits; + c->sub.code.tree = c->dtree; + LuTracevv((stderr, "inflate: length %u\n", c->len)); + c->mode = DIST; + case DIST: // i: get distance next + j = c->sub.code.need; + NEEDBITS(j) + t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); + DUMPBITS(t->bits) + e = (uInt)(t->exop); + if (e & 16) // distance + { + c->sub.copy.get = e & 15; + c->sub.copy.dist = t->base; + c->mode = DISTEXT; + break; + } + if ((e & 64) == 0) // next table + { + c->sub.code.need = e; + c->sub.code.tree = t + t->base; + break; + } + c->mode = BADCODE; // invalid code + z->msg = (char*)"invalid distance code"; + r = Z_DATA_ERROR; + LEAVE + case DISTEXT: // i: getting distance extra + j = c->sub.copy.get; + NEEDBITS(j) + c->sub.copy.dist += (uInt)b & inflate_mask[j]; + DUMPBITS(j) + LuTracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist)); + c->mode = COPY; + case COPY: // o: copying bytes in window, waiting for space + f = q - c->sub.copy.dist; + while (f < s->window) // modulo window size-"while" instead + f += s->end - s->window; // of "if" handles invalid distances + while (c->len) + { + NEEDOUT + OUTBYTE(*f++) + if (f == s->end) + f = s->window; + c->len--; + } + c->mode = START; + break; + case LIT: // o: got literal, waiting for output space + NEEDOUT + OUTBYTE(c->sub.lit) + c->mode = START; + break; + case WASH: // o: got eob, possibly more output + if (k > 7) // return unused byte, if any + { + //Assert(k < 16, "inflate_codes grabbed too many bytes") + k -= 8; + n++; + p--; // can always return one + } + FLUSH + if (s->read != s->write) + LEAVE + c->mode = END; + case END: + r = Z_STREAM_END; + LEAVE + case BADCODE: // x: got error + r = Z_DATA_ERROR; + LEAVE + default: + r = Z_STREAM_ERROR; + LEAVE + } +} + + +void inflate_codes_free(inflate_codes_statef *c,z_streamp z) +{ ZFREE(z, c); + LuTracev((stderr, "inflate: codes free\n")); +} + + + +// infblock.c -- interpret and process block types to last block +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h + +//struct inflate_codes_state {int dummy;}; // for buggy compilers + + + +// Table for deflate from PKZIP's appnote.txt. +const uInt border[] = { // Order of the bit length code lengths + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +// +// Notes beyond the 1.93a appnote.txt: +// +// 1. Distance pointers never point before the beginning of the output stream. +// 2. Distance pointers can point back across blocks, up to 32k away. +// 3. There is an implied maximum of 7 bits for the bit length table and +// 15 bits for the actual data. +// 4. If only one code exists, then it is encoded using one bit. (Zero +// would be more efficient, but perhaps a little confusing.) If two +// codes exist, they are coded using one bit each (0 and 1). +// 5. There is no way of sending zero distance codes--a dummy must be +// sent if there are none. (History: a pre 2.0 version of PKZIP would +// store blocks with no distance codes, but this was discovered to be +// too harsh a criterion.) Valid only for 1.93a. 2.04c does allow +// zero distance codes, which is sent as one code of zero bits in +// length. +// 6. There are up to 286 literal/length codes. Code 256 represents the +// end-of-block. Note however that the static length tree defines +// 288 codes just to fill out the Huffman codes. Codes 286 and 287 +// cannot be used though, since there is no length base or extra bits +// defined for them. Similarily, there are up to 30 distance codes. +// However, static trees define 32 codes (all 5 bits) to fill out the +// Huffman codes, but the last two had better not show up in the data. +// 7. Unzip can check dynamic Huffman blocks for complete code sets. +// The exception is that a single code would not be complete (see #4). +// 8. The five bits following the block type is really the number of +// literal codes sent minus 257. +// 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits +// (1+6+6). Therefore, to output three times the length, you output +// three codes (1+1+1), whereas to output four times the same length, +// you only need two codes (1+3). Hmm. +//10. In the tree reconstruction algorithm, Code = Code + Increment +// only if BitLength(i) is not zero. (Pretty obvious.) +//11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) +//12. Note: length code 284 can represent 227-258, but length code 285 +// really is 258. The last length deserves its own, short code +// since it gets used a lot in very redundant files. The length +// 258 is special since 258 - 3 (the min match length) is 255. +//13. The literal/length and distance code bit lengths are read as a +// single stream of lengths. It is possible (and advantageous) for +// a repeat code (16, 17, or 18) to go across the boundary between +// the two sets of lengths. + + +void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c) +{ + if (c != Z_NULL) + *c = s->check; + if (s->mode == IBM_BTREE || s->mode == IBM_DTREE) + ZFREE(z, s->sub.trees.blens); + if (s->mode == IBM_CODES) + inflate_codes_free(s->sub.decode.codes, z); + s->mode = IBM_TYPE; + s->bitk = 0; + s->bitb = 0; + s->read = s->write = s->window; + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0); + LuTracev((stderr, "inflate: blocks reset\n")); +} + + +inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w) +{ + inflate_blocks_statef *s; + + if ((s = (inflate_blocks_statef *)ZALLOC + (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL) + return s; + if ((s->hufts = + (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL) + { + ZFREE(z, s); + return Z_NULL; + } + if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL) + { + ZFREE(z, s->hufts); + ZFREE(z, s); + return Z_NULL; + } + s->end = s->window + w; + s->checkfn = c; + s->mode = IBM_TYPE; + LuTracev((stderr, "inflate: blocks allocated\n")); + inflate_blocks_reset(s, z, Z_NULL); + return s; +} + + +int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r) +{ + uInt t; // temporary storage + uLong b; // bit buffer + uInt k; // bits in bit buffer + Byte *p; // input data pointer + uInt n; // bytes available there + Byte *q; // output window write pointer + uInt m; // bytes to end of window or read pointer + + // copy input/output information to locals (UPDATE macro restores) + LOAD + + // process input based on current state + for(;;) switch (s->mode) + { + case IBM_TYPE: + NEEDBITS(3) + t = (uInt)b & 7; + s->last = t & 1; + switch (t >> 1) + { + case 0: // stored + LuTracev((stderr, "inflate: stored block%s\n", + s->last ? " (last)" : "")); + DUMPBITS(3) + t = k & 7; // go to byte boundary + DUMPBITS(t) + s->mode = IBM_LENS; // get length of stored block + break; + case 1: // fixed + LuTracev((stderr, "inflate: fixed codes block%s\n", + s->last ? " (last)" : "")); + { + uInt bl, bd; + const inflate_huft *tl, *td; + + inflate_trees_fixed(&bl, &bd, &tl, &td, z); + s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z); + if (s->sub.decode.codes == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + } + DUMPBITS(3) + s->mode = IBM_CODES; + break; + case 2: // dynamic + LuTracev((stderr, "inflate: dynamic codes block%s\n", + s->last ? " (last)" : "")); + DUMPBITS(3) + s->mode = IBM_TABLE; + break; + case 3: // illegal + DUMPBITS(3) + s->mode = IBM_BAD; + z->msg = (char*)"invalid block type"; + r = Z_DATA_ERROR; + LEAVE + } + break; + case IBM_LENS: + NEEDBITS(32) + if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) + { + s->mode = IBM_BAD; + z->msg = (char*)"invalid stored block lengths"; + r = Z_DATA_ERROR; + LEAVE + } + s->sub.left = (uInt)b & 0xffff; + b = k = 0; // dump bits + LuTracev((stderr, "inflate: stored length %u\n", s->sub.left)); + s->mode = s->sub.left ? IBM_STORED : (s->last ? IBM_DRY : IBM_TYPE); + break; + case IBM_STORED: + if (n == 0) + LEAVE + NEEDOUT + t = s->sub.left; + if (t > n) t = n; + if (t > m) t = m; + memcpy(q, p, t); + p += t; n -= t; + q += t; m -= t; + if ((s->sub.left -= t) != 0) + break; + LuTracev((stderr, "inflate: stored end, %lu total out\n", + z->total_out + (q >= s->read ? q - s->read : + (s->end - s->read) + (q - s->window)))); + s->mode = s->last ? IBM_DRY : IBM_TYPE; + break; + case IBM_TABLE: + NEEDBITS(14) + s->sub.trees.table = t = (uInt)b & 0x3fff; + // remove this section to workaround bug in pkzip + if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) + { + s->mode = IBM_BAD; + z->msg = (char*)"too many length or distance symbols"; + r = Z_DATA_ERROR; + LEAVE + } + // end remove + t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); + if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + DUMPBITS(14) + s->sub.trees.index = 0; + LuTracev((stderr, "inflate: table sizes ok\n")); + s->mode = IBM_BTREE; + case IBM_BTREE: + while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) + { + NEEDBITS(3) + s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7; + DUMPBITS(3) + } + while (s->sub.trees.index < 19) + s->sub.trees.blens[border[s->sub.trees.index++]] = 0; + s->sub.trees.bb = 7; + t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, + &s->sub.trees.tb, s->hufts, z); + if (t != Z_OK) + { + r = t; + if (r == Z_DATA_ERROR) + { + ZFREE(z, s->sub.trees.blens); + s->mode = IBM_BAD; + } + LEAVE + } + s->sub.trees.index = 0; + LuTracev((stderr, "inflate: bits tree ok\n")); + s->mode = IBM_DTREE; + case IBM_DTREE: + while (t = s->sub.trees.table, + s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) + { + inflate_huft *h; + uInt i, j, c; + + t = s->sub.trees.bb; + NEEDBITS(t) + h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); + t = h->bits; + c = h->base; + if (c < 16) + { + DUMPBITS(t) + s->sub.trees.blens[s->sub.trees.index++] = c; + } + else // c == 16..18 + { + i = c == 18 ? 7 : c - 14; + j = c == 18 ? 11 : 3; + NEEDBITS(t + i) + DUMPBITS(t) + j += (uInt)b & inflate_mask[i]; + DUMPBITS(i) + i = s->sub.trees.index; + t = s->sub.trees.table; + if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || + (c == 16 && i < 1)) + { + ZFREE(z, s->sub.trees.blens); + s->mode = IBM_BAD; + z->msg = (char*)"invalid bit length repeat"; + r = Z_DATA_ERROR; + LEAVE + } + c = c == 16 ? s->sub.trees.blens[i - 1] : 0; + do { + s->sub.trees.blens[i++] = c; + } while (--j); + s->sub.trees.index = i; + } + } + s->sub.trees.tb = Z_NULL; + { + uInt bl, bd; + inflate_huft *tl, *td; + inflate_codes_statef *c; + + bl = 9; // must be <= 9 for lookahead assumptions + bd = 6; // must be <= 9 for lookahead assumptions + t = s->sub.trees.table; + t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), + s->sub.trees.blens, &bl, &bd, &tl, &td, + s->hufts, z); + if (t != Z_OK) + { + if (t == (uInt)Z_DATA_ERROR) + { + ZFREE(z, s->sub.trees.blens); + s->mode = IBM_BAD; + } + r = t; + LEAVE + } + LuTracev((stderr, "inflate: trees ok\n")); + if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + s->sub.decode.codes = c; + } + ZFREE(z, s->sub.trees.blens); + s->mode = IBM_CODES; + case IBM_CODES: + UPDATE + if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) + return inflate_flush(s, z, r); + r = Z_OK; + inflate_codes_free(s->sub.decode.codes, z); + LOAD + LuTracev((stderr, "inflate: codes end, %lu total out\n", + z->total_out + (q >= s->read ? q - s->read : + (s->end - s->read) + (q - s->window)))); + if (!s->last) + { + s->mode = IBM_TYPE; + break; + } + s->mode = IBM_DRY; + case IBM_DRY: + FLUSH + if (s->read != s->write) + LEAVE + s->mode = IBM_DONE; + case IBM_DONE: + r = Z_STREAM_END; + LEAVE + case IBM_BAD: + r = Z_DATA_ERROR; + LEAVE + default: + r = Z_STREAM_ERROR; + LEAVE + } +} + + +int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z) +{ + inflate_blocks_reset(s, z, Z_NULL); + ZFREE(z, s->window); + ZFREE(z, s->hufts); + ZFREE(z, s); + LuTracev((stderr, "inflate: blocks freed\n")); + return Z_OK; +} + + + +// inftrees.c -- generate Huffman trees for efficient decoding +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h +// + + + +// allready added in wxWidgets +//extern const char inflate_copyright[] = +// " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; +// If you use the zlib library in a product, an acknowledgment is welcome +// in the documentation of your product. If for some reason you cannot +// include such an acknowledgment, I would appreciate that you keep this +// copyright string in the executable of your product. + + + +int huft_build ( + uInt *, // code lengths in bits + uInt, // number of codes + uInt, // number of "simple" codes + const uInt *, // list of base values for non-simple codes + const uInt *, // list of extra bits for non-simple codes + inflate_huft **,// result: starting table + uInt *, // maximum lookup bits (returns actual) + inflate_huft *, // space for trees + uInt *, // hufts used in space + uInt * ); // space for values + +// Tables for deflate from PKZIP's appnote.txt. +const uInt cplens[31] = { // Copy lengths for literal codes 257..285 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + // see note #13 above about 258 +const uInt cplext[31] = { // Extra bits for literal codes 257..285 + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; // 112==invalid +const uInt cpdist[30] = { // Copy offsets for distance codes 0..29 + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577}; +const uInt cpdext[30] = { // Extra bits for distance codes + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13}; + +// +// Huffman code decoding is performed using a multi-level table lookup. +// The fastest way to decode is to simply build a lookup table whose +// size is determined by the longest code. However, the time it takes +// to build this table can also be a factor if the data being decoded +// is not very long. The most common codes are necessarily the +// shortest codes, so those codes dominate the decoding time, and hence +// the speed. The idea is you can have a shorter table that decodes the +// shorter, more probable codes, and then point to subsidiary tables for +// the longer codes. The time it costs to decode the longer codes is +// then traded against the time it takes to make longer tables. +// +// This results of this trade are in the variables lbits and dbits +// below. lbits is the number of bits the first level table for literal/ +// length codes can decode in one step, and dbits is the same thing for +// the distance codes. Subsequent tables are also less than or equal to +// those sizes. These values may be adjusted either when all of the +// codes are shorter than that, in which case the longest code length in +// bits is used, or when the shortest code is *longer* than the requested +// table size, in which case the length of the shortest code in bits is +// used. +// +// There are two different values for the two tables, since they code a +// different number of possibilities each. The literal/length table +// codes 286 possible values, or in a flat code, a little over eight +// bits. The distance table codes 30 possible values, or a little less +// than five bits, flat. The optimum values for speed end up being +// about one bit more than those, so lbits is 8+1 and dbits is 5+1. +// The optimum values may differ though from machine to machine, and +// possibly even between compilers. Your mileage may vary. +// + + +// If BMAX needs to be larger than 16, then h and x[] should be uLong. +#define BMAX 15 // maximum bit length of any code + +int huft_build( +uInt *b, // code lengths in bits (all assumed <= BMAX) +uInt n, // number of codes (assumed <= 288) +uInt s, // number of simple-valued codes (0..s-1) +const uInt *d, // list of base values for non-simple codes +const uInt *e, // list of extra bits for non-simple codes +inflate_huft * *t, // result: starting table +uInt *m, // maximum lookup bits, returns actual +inflate_huft *hp, // space for trees +uInt *hn, // hufts used in space +uInt *v) // working area: values in order of bit length +// Given a list of code lengths and a maximum table size, make a set of +// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR +// if the given code set is incomplete (the tables are still built in this +// case), or Z_DATA_ERROR if the input is invalid. +{ + + uInt a; // counter for codes of length k + uInt c[BMAX+1]; // bit length count table + uInt f; // i repeats in table every f entries + int g; // maximum code length + int h; // table level + register uInt i; // counter, current code + register uInt j; // counter + register int k; // number of bits in current code + int l; // bits per table (returned in m) + uInt mask; // (1 << w) - 1, to avoid cc -O bug on HP + register uInt *p; // pointer into c[], b[], or v[] + inflate_huft *q; // points to current table + struct inflate_huft_s r; // table entry for structure assignment + inflate_huft *u[BMAX]; // table stack + register int w; // bits before this table == (l * h) + uInt x[BMAX+1]; // bit offsets, then code stack + uInt *xp; // pointer into x + int y; // number of dummy codes added + uInt z; // number of entries in current table + + + // Generate counts for each bit length + p = c; +#define C0 *p++ = 0; +#define C2 C0 C0 C0 C0 +#define C4 C2 C2 C2 C2 + C4; p; // clear c[]--assume BMAX+1 is 16 + p = b; i = n; + do { + c[*p++]++; // assume all entries <= BMAX + } while (--i); + if (c[0] == n) // null input--all zero length codes + { + *t = (inflate_huft *)Z_NULL; + *m = 0; + return Z_OK; + } + + + // Find minimum and maximum length, bound *m by those + l = *m; + for (j = 1; j <= BMAX; j++) + if (c[j]) + break; + k = j; // minimum code length + if ((uInt)l < j) + l = j; + for (i = BMAX; i; i--) + if (c[i]) + break; + g = i; // maximum code length + if ((uInt)l > i) + l = i; + *m = l; + + + // Adjust last length count to fill out codes, if needed + for (y = 1 << j; j < i; j++, y <<= 1) + if ((y -= c[j]) < 0) + return Z_DATA_ERROR; + if ((y -= c[i]) < 0) + return Z_DATA_ERROR; + c[i] += y; + + + // Generate starting offsets into the value table for each length + x[1] = j = 0; + p = c + 1; xp = x + 2; + while (--i) { // note that i == g from above + *xp++ = (j += *p++); + } + + + // Make a table of values in order of bit lengths + p = b; i = 0; + do { + if ((j = *p++) != 0) + v[x[j]++] = i; + } while (++i < n); + n = x[g]; // set n to length of v + + + // Generate the Huffman codes and for each, make the table entries + x[0] = i = 0; // first Huffman code is zero + p = v; // grab values in bit order + h = -1; // no tables yet--level -1 + w = -l; // bits decoded == (l * h) + u[0] = (inflate_huft *)Z_NULL; // just to keep compilers happy + q = (inflate_huft *)Z_NULL; // ditto + z = 0; // ditto + + // go through the bit lengths (k already is bits in shortest code) + for (; k <= g; k++) + { + a = c[k]; + while (a--) + { + // here i is the Huffman code of length k bits for value *p + // make tables up to required level + while (k > w + l) + { + h++; + w += l; // previous table always l bits + + // compute minimum size table less than or equal to l bits + z = g - w; + z = z > (uInt)l ? l : z; // table size upper limit + if ((f = 1 << (j = k - w)) > a + 1) // try a k-w bit table + { // too few codes for k-w bit table + f -= a + 1; // deduct codes from patterns left + xp = c + k; + if (j < z) + while (++j < z) // try smaller tables up to z bits + { + if ((f <<= 1) <= *++xp) + break; // enough codes to use up j bits + f -= *xp; // else deduct codes from patterns + } + } + z = 1 << j; // table entries for j-bit table + + // allocate new table + if (*hn + z > MANY) // (note: doesn't matter for fixed) + return Z_DATA_ERROR; // overflow of MANY + u[h] = q = hp + *hn; + *hn += z; + + // connect to last table, if there is one + if (h) + { + x[h] = i; // save pattern for backing up + r.bits = (Byte)l; // bits to dump before this table + r.exop = (Byte)j; // bits in this table + j = i >> (w - l); + r.base = (uInt)(q - u[h-1] - j); // offset to this table + u[h-1][j] = r; // connect to last table + } + else + *t = q; // first table is returned result + } + + // set up table entry in r + r.bits = (Byte)(k - w); + if (p >= v + n) + r.exop = 128 + 64; // out of values--invalid code + else if (*p < s) + { + r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); // 256 is end-of-block + r.base = *p++; // simple code is just the value + } + else + { + r.exop = (Byte)(e[*p - s] + 16 + 64);// non-simple--look up in lists + r.base = d[*p++ - s]; + } + + // fill code-like entries with r + f = 1 << (k - w); + for (j = i >> w; j < z; j += f) + q[j] = r; + + // backwards increment the k-bit code i + for (j = 1 << (k - 1); i & j; j >>= 1) + i ^= j; + i ^= j; + + // backup over finished tables + mask = (1 << w) - 1; // needed on HP, cc -O bug + while ((i & mask) != x[h]) + { + h--; // don't need to update q + w -= l; + mask = (1 << w) - 1; + } + } + } + + + // Return Z_BUF_ERROR if we were given an incomplete table + return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; +} + + +int inflate_trees_bits( +uInt *c, // 19 code lengths +uInt *bb, // bits tree desired/actual depth +inflate_huft * *tb, // bits tree result +inflate_huft *hp, // space for trees +z_streamp z) // for messages +{ + int r; + uInt hn = 0; // hufts used in space + uInt *v; // work area for huft_build + + if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL) + return Z_MEM_ERROR; + r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL, + tb, bb, hp, &hn, v); + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed dynamic bit lengths tree"; + else if (r == Z_BUF_ERROR || *bb == 0) + { + z->msg = (char*)"incomplete dynamic bit lengths tree"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; +} + + +int inflate_trees_dynamic( +uInt nl, // number of literal/length codes +uInt nd, // number of distance codes +uInt *c, // that many (total) code lengths +uInt *bl, // literal desired/actual bit depth +uInt *bd, // distance desired/actual bit depth +inflate_huft * *tl, // literal/length tree result +inflate_huft * *td, // distance tree result +inflate_huft *hp, // space for trees +z_streamp z) // for messages +{ + int r; + uInt hn = 0; // hufts used in space + uInt *v; // work area for huft_build + + // allocate work area + if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) + return Z_MEM_ERROR; + + // build literal/length tree + r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v); + if (r != Z_OK || *bl == 0) + { + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed literal/length tree"; + else if (r != Z_MEM_ERROR) + { + z->msg = (char*)"incomplete literal/length tree"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; + } + + // build distance tree + r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v); + if (r != Z_OK || (*bd == 0 && nl > 257)) + { + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed distance tree"; + else if (r == Z_BUF_ERROR) { + z->msg = (char*)"incomplete distance tree"; + r = Z_DATA_ERROR; + } + else if (r != Z_MEM_ERROR) + { + z->msg = (char*)"empty distance tree with lengths"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; + } + + // done + ZFREE(z, v); + return Z_OK; +} + + + + + +int inflate_trees_fixed( +uInt *bl, // literal desired/actual bit depth +uInt *bd, // distance desired/actual bit depth +const inflate_huft * * tl, // literal/length tree result +const inflate_huft * *td, // distance tree result +z_streamp ) // for memory allocation +{ + *bl = fixed_bl; + *bd = fixed_bd; + *tl = fixed_tl; + *td = fixed_td; + return Z_OK; +} + + +// inffast.c -- process literals and length/distance pairs fast +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h +// + + +//struct inflate_codes_state {int dummy;}; // for buggy compilers + + +// macros for bit input with no checking and for returning unused bytes +#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;} + +// Called with number of bytes left to write in window at least 258 +// (the maximum string length) and number of input bytes available +// at least ten. The ten bytes are six bytes for the longest length/ +// distance pair plus four bytes for overloading the bit buffer. + +int inflate_fast( +uInt bl, uInt bd, +const inflate_huft *tl, +const inflate_huft *td, // need separate declaration for Borland C++ +inflate_blocks_statef *s, +z_streamp z) +{ + const inflate_huft *t; // temporary pointer + uInt e; // extra bits or operation + uLong b; // bit buffer + uInt k; // bits in bit buffer + Byte *p; // input data pointer + uInt n; // bytes available there + Byte *q; // output window write pointer + uInt m; // bytes to end of window or read pointer + uInt ml; // mask for literal/length tree + uInt md; // mask for distance tree + uInt c; // bytes to copy + uInt d; // distance back to copy from + Byte *r; // copy source pointer + + // load input, output, bit values + LOAD + + // initialize masks + ml = inflate_mask[bl]; + md = inflate_mask[bd]; + + // do until not enough input or output space for fast loop + do { // assume called with m >= 258 && n >= 10 + // get literal/length code + GRABBITS(20) // max bits for literal/length code + if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) + { + DUMPBITS(t->bits) + LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: * literal '%c'\n" : + "inflate: * literal 0x%02x\n", t->base)); + *q++ = (Byte)t->base; + m--; + continue; + } + for (;;) { + DUMPBITS(t->bits) + if (e & 16) + { + // get extra bits for length + e &= 15; + c = t->base + ((uInt)b & inflate_mask[e]); + DUMPBITS(e) + LuTracevv((stderr, "inflate: * length %u\n", c)); + + // decode distance base of block to copy + GRABBITS(15); // max bits for distance code + e = (t = td + ((uInt)b & md))->exop; + for (;;) { + DUMPBITS(t->bits) + if (e & 16) + { + // get extra bits to add to distance base + e &= 15; + GRABBITS(e) // get extra bits (up to 13) + d = t->base + ((uInt)b & inflate_mask[e]); + DUMPBITS(e) + LuTracevv((stderr, "inflate: * distance %u\n", d)); + + // do the copy + m -= c; + r = q - d; + if (r < s->window) // wrap if needed + { + do { + r += s->end - s->window; // force pointer in window + } while (r < s->window); // covers invalid distances + e = (uInt) (s->end - r); + if (c > e) + { + c -= e; // wrapped copy + do { + *q++ = *r++; + } while (--e); + r = s->window; + do { + *q++ = *r++; + } while (--c); + } + else // normal copy + { + *q++ = *r++; c--; + *q++ = *r++; c--; + do { + *q++ = *r++; + } while (--c); + } + } + else /* normal copy */ + { + *q++ = *r++; c--; + *q++ = *r++; c--; + do { + *q++ = *r++; + } while (--c); + } + break; + } + else if ((e & 64) == 0) + { + t += t->base; + e = (t += ((uInt)b & inflate_mask[e]))->exop; + } + else + { + z->msg = (char*)"invalid distance code"; + UNGRAB + UPDATE + return Z_DATA_ERROR; + } + }; + break; + } + if ((e & 64) == 0) + { + t += t->base; + if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0) + { + DUMPBITS(t->bits) + LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: * literal '%c'\n" : + "inflate: * literal 0x%02x\n", t->base)); + *q++ = (Byte)t->base; + m--; + break; + } + } + else if (e & 32) + { + LuTracevv((stderr, "inflate: * end of block\n")); + UNGRAB + UPDATE + return Z_STREAM_END; + } + else + { + z->msg = (char*)"invalid literal/length code"; + UNGRAB + UPDATE + return Z_DATA_ERROR; + } + }; + } while (m >= 258 && n >= 10); + + // not enough input or output--restore pointers and return + UNGRAB + UPDATE + return Z_OK; +} + + + + + + +// crc32.c -- compute the CRC-32 of a data stream +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h + +// @(#) $Id$ + + + + + + +// Table of CRC-32's of all single-byte values (made by make_crc_table) +const uLong crc_table[256] = { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, + 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, + 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, + 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, + 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, + 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, + 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, + 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, + 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, + 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, + 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, + 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, + 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, + 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, + 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, + 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, + 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, + 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, + 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, + 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, + 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, + 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, + 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, + 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, + 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, + 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, + 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, + 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, + 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, + 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, + 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, + 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, + 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, + 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, + 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, + 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, + 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, + 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, + 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, + 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, + 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, + 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, + 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, + 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, + 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, + 0x2d02ef8dL +}; + +const uLong * get_crc_table() +{ return (const uLong *)crc_table; +} + +#define CRC_DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); +#define CRC_DO2(buf) CRC_DO1(buf); CRC_DO1(buf); +#define CRC_DO4(buf) CRC_DO2(buf); CRC_DO2(buf); +#define CRC_DO8(buf) CRC_DO4(buf); CRC_DO4(buf); + +uLong ucrc32(uLong crc, const Byte *buf, uInt len) +{ if (buf == Z_NULL) return 0L; + crc = crc ^ 0xffffffffL; + while (len >= 8) {CRC_DO8(buf); len -= 8;} + if (len) do {CRC_DO1(buf);} while (--len); + return crc ^ 0xffffffffL; +} + + + +// ============================================================= +// some decryption routines +#define CRC32(c, b) (crc_table[((int)(c)^(b))&0xff]^((c)>>8)) +void Uupdate_keys(unsigned long *keys, char c) +{ keys[0] = CRC32(keys[0],c); + keys[1] += keys[0] & 0xFF; + keys[1] = keys[1]*134775813L +1; + keys[2] = CRC32(keys[2], keys[1] >> 24); +} +char Udecrypt_byte(unsigned long *keys) +{ unsigned temp = ((unsigned)keys[2] & 0xffff) | 2; + return (char)(((temp * (temp ^ 1)) >> 8) & 0xff); +} +char zdecode(unsigned long *keys, char c) +{ c^=Udecrypt_byte(keys); + Uupdate_keys(keys,c); + return c; +} + + + +// adler32.c -- compute the Adler-32 checksum of a data stream +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h + +// @(#) $Id$ + + +#define BASE 65521L // largest prime smaller than 65536 +#define NMAX 5552 +// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 + +#define AD_DO1(buf,i) {s1 += buf[i]; s2 += s1;} +#define AD_DO2(buf,i) AD_DO1(buf,i); AD_DO1(buf,i+1); +#define AD_DO4(buf,i) AD_DO2(buf,i); AD_DO2(buf,i+2); +#define AD_DO8(buf,i) AD_DO4(buf,i); AD_DO4(buf,i+4); +#define AD_DO16(buf) AD_DO8(buf,0); AD_DO8(buf,8); + +// ========================================================================= +uLong adler32(uLong adler, const Byte *buf, uInt len) +{ + unsigned long s1 = adler & 0xffff; + unsigned long s2 = (adler >> 16) & 0xffff; + int k; + + if (buf == Z_NULL) return 1L; + + while (len > 0) { + k = len < NMAX ? len : NMAX; + len -= k; + while (k >= 16) { + AD_DO16(buf); + buf += 16; + k -= 16; + } + if (k != 0) do { + s1 += *buf++; + s2 += s1; + } while (--k); + s1 %= BASE; + s2 %= BASE; + } + return (s2 << 16) | s1; +} + + + +// zutil.c -- target dependent utility functions for the compression library +// Copyright (C) 1995-1998 Jean-loup Gailly. +// For conditions of distribution and use, see copyright notice in zlib.h +// @(#) $Id$ + + + + + + +const char * zlibVersion() +{ + return ZLIB_VERSION; +} + +// exported to allow conversion of error code to string for compress() and +// uncompress() +const char * zError(int err) +{ return ERR_MSG(err); +} + + + + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) items += size - size; // make compiler happy + return (voidpf)calloc(items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + zfree(ptr); + if (opaque) return; // make compiler happy +} + + + +// inflate.c -- zlib interface to inflate modules +// Copyright (C) 1995-1998 Mark Adler +// For conditions of distribution and use, see copyright notice in zlib.h + +//struct inflate_blocks_state {int dummy;}; // for buggy compilers + +typedef enum { + IM_METHOD, // waiting for method byte + IM_FLAG, // waiting for flag byte + IM_DICT4, // four dictionary check bytes to go + IM_DICT3, // three dictionary check bytes to go + IM_DICT2, // two dictionary check bytes to go + IM_DICT1, // one dictionary check byte to go + IM_DICT0, // waiting for inflateSetDictionary + IM_BLOCKS, // decompressing blocks + IM_CHECK4, // four check bytes to go + IM_CHECK3, // three check bytes to go + IM_CHECK2, // two check bytes to go + IM_CHECK1, // one check byte to go + IM_DONE, // finished check, done + IM_BAD} // got an error--stay here +inflate_mode; + +// inflate private state +struct internal_state { + + // mode + inflate_mode mode; // current inflate mode + + // mode dependent information + union { + uInt method; // if IM_FLAGS, method byte + struct { + uLong was; // computed check value + uLong need; // stream check value + } check; // if CHECK, check values to compare + uInt marker; // if IM_BAD, inflateSync's marker bytes count + } sub; // submode + + // mode independent information + int nowrap; // flag for no wrapper + uInt wbits; // log2(window size) (8..15, defaults to 15) + inflate_blocks_statef + *blocks; // current inflate_blocks state + +}; + +int inflateReset(z_streamp z) +{ + if (z == Z_NULL || z->state == Z_NULL) + return Z_STREAM_ERROR; + z->total_in = z->total_out = 0; + z->msg = Z_NULL; + z->state->mode = z->state->nowrap ? IM_BLOCKS : IM_METHOD; + inflate_blocks_reset(z->state->blocks, z, Z_NULL); + LuTracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int inflateEnd(z_streamp z) +{ + if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) + return Z_STREAM_ERROR; + if (z->state->blocks != Z_NULL) + inflate_blocks_free(z->state->blocks, z); + ZFREE(z, z->state); + z->state = Z_NULL; + LuTracev((stderr, "inflate: end\n")); + return Z_OK; +} + + +int inflateInit2(z_streamp z) +{ const char *version = ZLIB_VERSION; int stream_size = sizeof(z_stream); + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != sizeof(z_stream)) return Z_VERSION_ERROR; + + int w = -15; // MAX_WBITS: 32K LZ77 window. + // Warning: reducing MAX_WBITS makes minigzip unable to extract .gz files created by gzip. + // The memory requirements for deflate are (in bytes): + // (1 << (windowBits+2)) + (1 << (memLevel+9)) + // that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + // plus a few kilobytes for small objects. For example, if you want to reduce + // the default memory requirements from 256K to 128K, compile with + // make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + // Of course this will generally degrade compression (there's no free lunch). + // + // The memory requirements for inflate are (in bytes) 1 << windowBits + // that is, 32K for windowBits=15 (default value) plus a few kilobytes + // for small objects. + + // initialize state + if (z == Z_NULL) return Z_STREAM_ERROR; + z->msg = Z_NULL; + if (z->zalloc == Z_NULL) + { + z->zalloc = zcalloc; + z->opaque = (voidpf)0; + } + if (z->zfree == Z_NULL) z->zfree = zcfree; + if ((z->state = (struct internal_state *) + ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL) + return Z_MEM_ERROR; + z->state->blocks = Z_NULL; + + // handle undocumented nowrap option (no zlib header or check) + z->state->nowrap = 0; + if (w < 0) + { + w = - w; + z->state->nowrap = 1; + } + + // set window size + if (w < 8 || w > 15) + { + inflateEnd(z); + return Z_STREAM_ERROR; + } + z->state->wbits = (uInt)w; + + // create inflate_blocks state + if ((z->state->blocks = + inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w)) + == Z_NULL) + { + inflateEnd(z); + return Z_MEM_ERROR; + } + LuTracev((stderr, "inflate: allocated\n")); + + // reset state + inflateReset(z); + return Z_OK; +} + + + +#define IM_NEEDBYTE {if(z->avail_in==0)return r;r=f;} +#define IM_NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) + +int inflate(z_streamp z, int f) +{ + int r; + uInt b; + + if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL) + return Z_STREAM_ERROR; + f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; + r = Z_BUF_ERROR; + for (;;) switch (z->state->mode) + { + case IM_METHOD: + IM_NEEDBYTE + if (((z->state->sub.method = IM_NEXTBYTE) & 0xf) != Z_DEFLATED) + { + z->state->mode = IM_BAD; + z->msg = (char*)"unknown compression method"; + z->state->sub.marker = 5; // can't try inflateSync + break; + } + if ((z->state->sub.method >> 4) + 8 > z->state->wbits) + { + z->state->mode = IM_BAD; + z->msg = (char*)"invalid window size"; + z->state->sub.marker = 5; // can't try inflateSync + break; + } + z->state->mode = IM_FLAG; + case IM_FLAG: + IM_NEEDBYTE + b = IM_NEXTBYTE; + if (((z->state->sub.method << 8) + b) % 31) + { + z->state->mode = IM_BAD; + z->msg = (char*)"incorrect header check"; + z->state->sub.marker = 5; // can't try inflateSync + break; + } + LuTracev((stderr, "inflate: zlib header ok\n")); + if (!(b & PRESET_DICT)) + { + z->state->mode = IM_BLOCKS; + break; + } + z->state->mode = IM_DICT4; + case IM_DICT4: + IM_NEEDBYTE + z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24; + z->state->mode = IM_DICT3; + case IM_DICT3: + IM_NEEDBYTE + z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16; + z->state->mode = IM_DICT2; + case IM_DICT2: + IM_NEEDBYTE + z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8; + z->state->mode = IM_DICT1; + case IM_DICT1: + IM_NEEDBYTE; r; + z->state->sub.check.need += (uLong)IM_NEXTBYTE; + z->adler = z->state->sub.check.need; + z->state->mode = IM_DICT0; + return Z_NEED_DICT; + case IM_DICT0: + z->state->mode = IM_BAD; + z->msg = (char*)"need dictionary"; + z->state->sub.marker = 0; // can try inflateSync + return Z_STREAM_ERROR; + case IM_BLOCKS: + r = inflate_blocks(z->state->blocks, z, r); + if (r == Z_DATA_ERROR) + { + z->state->mode = IM_BAD; + z->state->sub.marker = 0; // can try inflateSync + break; + } + if (r == Z_OK) + r = f; + if (r != Z_STREAM_END) + return r; + r = f; + inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was); + if (z->state->nowrap) + { + z->state->mode = IM_DONE; + break; + } + z->state->mode = IM_CHECK4; + case IM_CHECK4: + IM_NEEDBYTE + z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24; + z->state->mode = IM_CHECK3; + case IM_CHECK3: + IM_NEEDBYTE + z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16; + z->state->mode = IM_CHECK2; + case IM_CHECK2: + IM_NEEDBYTE + z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8; + z->state->mode = IM_CHECK1; + case IM_CHECK1: + IM_NEEDBYTE + z->state->sub.check.need += (uLong)IM_NEXTBYTE; + + if (z->state->sub.check.was != z->state->sub.check.need) + { + z->state->mode = IM_BAD; + z->msg = (char*)"incorrect data check"; + z->state->sub.marker = 5; // can't try inflateSync + break; + } + LuTracev((stderr, "inflate: zlib check ok\n")); + z->state->mode = IM_DONE; + case IM_DONE: + return Z_STREAM_END; + case IM_BAD: + return Z_DATA_ERROR; + default: + return Z_STREAM_ERROR; + } +} + + + + + +// unzip.c -- IO on .zip files using zlib +// Version 0.15 beta, Mar 19th, 1998, +// Read unzip.h for more info + + + + +#define UNZ_BUFSIZE (16384) +#define UNZ_MAXFILENAMEINZIP (256) +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) + + + + +const char unz_copyright[] = " unzip 0.15 Copyright 1998 Gilles Vollant "; + +// unz_file_info_interntal contain internal info about a file in zipfile +typedef struct unz_file_info_internal_s +{ + uLong offset_curfile;// relative offset of local header 4 bytes +} unz_file_info_internal; + + +typedef struct +{ bool is_handle; // either a handle or memory + bool canseek; + // for handles: + HANDLE h; bool herr; unsigned long initial_offset; bool mustclosehandle; + // for memory: + void *buf; unsigned int len,pos; // if it's a memory block +} LUFILE; + + +LUFILE *lufopen(void *z,unsigned int len,DWORD flags,ZRESULT *err) +{ if (flags!=ZIP_HANDLE && flags!=ZIP_FILENAME && flags!=ZIP_MEMORY) {*err=ZR_ARGS; return NULL;} + // + HANDLE h=0; bool canseek=false; *err=ZR_OK; + bool mustclosehandle=false; + if (flags==ZIP_HANDLE||flags==ZIP_FILENAME) + { if (flags==ZIP_HANDLE) + { HANDLE hf = z; + h=hf; mustclosehandle=false; +#ifdef DuplicateHandle + BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&h,0,FALSE,DUPLICATE_SAME_ACCESS); + if (!res) mustclosehandle=true; +#endif + } + else + { h=CreateFile((const TCHAR*)z,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); + if (h==INVALID_HANDLE_VALUE) {*err=ZR_NOFILE; return NULL;} + mustclosehandle=true; + } + // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE. + DWORD res = SetFilePointer(h,0,0,FILE_CURRENT); + canseek = (res!=0xFFFFFFFF); + } + LUFILE *lf = new LUFILE; + if (flags==ZIP_HANDLE||flags==ZIP_FILENAME) + { lf->is_handle=true; lf->mustclosehandle=mustclosehandle; + lf->canseek=canseek; + lf->h=h; lf->herr=false; + lf->initial_offset=0; + if (canseek) lf->initial_offset = SetFilePointer(h,0,NULL,FILE_CURRENT); + } + else + { lf->is_handle=false; + lf->canseek=true; + lf->mustclosehandle=false; + lf->buf=z; lf->len=len; lf->pos=0; lf->initial_offset=0; + } + *err=ZR_OK; + return lf; +} + + +int lufclose(LUFILE *stream) +{ if (stream==NULL) return EOF; + if (stream->mustclosehandle) CloseHandle(stream->h); + delete stream; + return 0; +} + +int luferror(LUFILE *stream) +{ if (stream->is_handle && stream->herr) return 1; + else return 0; +} + +long int luftell(LUFILE *stream) +{ if (stream->is_handle && stream->canseek) return SetFilePointer(stream->h,0,NULL,FILE_CURRENT)-stream->initial_offset; + else if (stream->is_handle) return 0; + else return stream->pos; +} + +int lufseek(LUFILE *stream, long offset, int whence) +{ if (stream->is_handle && stream->canseek) + { if (whence==SEEK_SET) SetFilePointer(stream->h,stream->initial_offset+offset,0,FILE_BEGIN); + else if (whence==SEEK_CUR) SetFilePointer(stream->h,offset,NULL,FILE_CURRENT); + else if (whence==SEEK_END) SetFilePointer(stream->h,offset,NULL,FILE_END); + else return 19; // EINVAL + return 0; + } + else if (stream->is_handle) return 29; // ESPIPE + else + { if (whence==SEEK_SET) stream->pos=offset; + else if (whence==SEEK_CUR) stream->pos+=offset; + else if (whence==SEEK_END) stream->pos=stream->len+offset; + return 0; + } +} + + +size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream) +{ unsigned int toread = (unsigned int)(size*n); + if (stream->is_handle) + { DWORD red; BOOL res = ReadFile(stream->h,ptr,toread,&red,NULL); + if (!res) stream->herr=true; + return red/size; + } + if (stream->pos+toread > stream->len) toread = stream->len-stream->pos; + memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread; + stream->pos += red; + return red/size; +} + + + + +// file_in_zip_read_info_s contain internal information about a file in zipfile, +// when reading and decompress it +typedef struct +{ + char *read_buffer; // internal buffer for compressed data + z_stream stream; // zLib stream structure for inflate + + uLong pos_in_zipfile; // position in byte on the zipfile, for fseek + uLong stream_initialised; // flag set if stream structure is initialised + + uLong offset_local_extrafield;// offset of the local extra field + uInt size_local_extrafield;// size of the local extra field + uLong pos_local_extrafield; // position in the local extra field in read + + uLong crc32; // crc32 of all data uncompressed + uLong crc32_wait; // crc32 we must obtain after decompress all + uLong rest_read_compressed; // number of byte to be decompressed + uLong rest_read_uncompressed;//number of byte to be obtained after decomp + LUFILE* file; // io structore of the zipfile + uLong compression_method; // compression method (0==store) + uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx) + bool encrypted; // is it encrypted? + unsigned long keys[3]; // decryption keys, initialized by unzOpenCurrentFile + int encheadleft; // the first call(s) to unzReadCurrentFile will read this many encryption-header bytes first + char crcenctest; // if encrypted, we'll check the encryption buffer against this +} file_in_zip_read_info_s; + + +// unz_s contain internal information about the zipfile +typedef struct +{ + LUFILE* file; // io structore of the zipfile + unz_global_info gi; // public global information + uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx) + uLong num_file; // number of the current file in the zipfile + uLong pos_in_central_dir; // pos of the current file in the central dir + uLong current_file_ok; // flag about the usability of the current file + uLong central_pos; // position of the beginning of the central dir + + uLong size_central_dir; // size of the central directory + uLong offset_central_dir; // offset of start of central directory with respect to the starting disk number + + unz_file_info cur_file_info; // public info about the current file in zip + unz_file_info_internal cur_file_info_internal; // private info about it + file_in_zip_read_info_s* pfile_in_zip_read; // structure about the current file if we are decompressing it +} unz_s, *unzFile; + + +int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity); +// Compare two filename (fileName1,fileName2). + +z_off_t unztell (unzFile file); +// Give the current position in uncompressed data + +int unzeof (unzFile file); +// return 1 if the end of file was reached, 0 elsewhere + +int unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len); +// Read extra field from the current file (opened by unzOpenCurrentFile) +// This is the local-header version of the extra field (sometimes, there is +// more info in the local-header version than in the central-header) +// +// if buf==NULL, it return the size of the local extra field +// +// if buf!=NULL, len is the size of the buffer, the extra header is copied in +// buf. +// the return value is the number of bytes copied in buf, or (if <0) +// the error code + + + +// =========================================================================== +// Read a byte from a gz_stream; update next_in and avail_in. Return EOF +// for end of file. +// IN assertion: the stream s has been sucessfully opened for reading. + +int unzlocal_getByte(LUFILE *fin,int *pi) +{ unsigned char c; + int err = (int)lufread(&c, 1, 1, fin); + if (err==1) + { *pi = (int)c; + return UNZ_OK; + } + else + { if (luferror(fin)) return UNZ_ERRNO; + else return UNZ_EOF; + } +} + + +// =========================================================================== +// Reads a long in LSB order from the given gz_stream. Sets +int unzlocal_getShort (LUFILE *fin,uLong *pX) +{ + uLong x ; + int i; + int err; + + err = unzlocal_getByte(fin,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unzlocal_getByte(fin,&i); + x += ((uLong)i)<<8; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +int unzlocal_getLong (LUFILE *fin,uLong *pX) +{ + uLong x ; + int i; + int err; + + err = unzlocal_getByte(fin,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unzlocal_getByte(fin,&i); + x += ((uLong)i)<<8; + + if (err==UNZ_OK) + err = unzlocal_getByte(fin,&i); + x += ((uLong)i)<<16; + + if (err==UNZ_OK) + err = unzlocal_getByte(fin,&i); + x += ((uLong)i)<<24; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + + +// My own strcmpi / strcasecmp +int strcmpcasenosensitive_internal (const char* fileName1,const char *fileName2) +{ + for (;;) + { + char c1=*(fileName1++); + char c2=*(fileName2++); + if ((c1>='a') && (c1<='z')) + c1 -= (char)0x20; + if ((c2>='a') && (c2<='z')) + c2 -= (char)0x20; + if (c1=='\0') + return ((c2=='\0') ? 0 : -1); + if (c2=='\0') + return 1; + if (c1c2) + return 1; + } +} + + + + +// +// Compare two filename (fileName1,fileName2). +// If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) +// If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp) +// +int unzStringFileNameCompare (const char*fileName1,const char*fileName2,int iCaseSensitivity) +{ if (iCaseSensitivity==1) return strcmp(fileName1,fileName2); + else return strcmpcasenosensitive_internal(fileName1,fileName2); +} + +#define BUFREADCOMMENT (0x400) + + +// Locate the Central directory of a zipfile (at the end, just before +// the global comment). Lu bugfix 2005.07.26 - returns 0xFFFFFFFF if not found, +// rather than 0, since 0 is a valid central-dir-location for an empty zipfile. +uLong unzlocal_SearchCentralDir(LUFILE *fin) +{ if (lufseek(fin,0,SEEK_END) != 0) return 0xFFFFFFFF; + uLong uSizeFile = luftell(fin); + + uLong uMaxBack=0xffff; // maximum size of global comment + if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; + + unsigned char *buf = (unsigned char*)zmalloc(BUFREADCOMMENT+4); + if (buf==NULL) return 0xFFFFFFFF; + uLong uPosFound=0xFFFFFFFF; + + uLong uBackRead = 4; + while (uBackReaduMaxBack) uBackRead = uMaxBack; + else uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); + if (lufseek(fin,uReadPos,SEEK_SET)!=0) break; + if (lufread(buf,(uInt)uReadSize,1,fin)!=1) break; + for (i=(int)uReadSize-3; (i--)>=0;) + { if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { uPosFound = uReadPos+i; break; + } + } + if (uPosFound!=0) break; + } + if (buf) zfree(buf); + return uPosFound; +} + + +int unzGoToFirstFile (unzFile file); +int unzCloseCurrentFile (unzFile file); + +// Open a Zip file. +// If the zipfile cannot be opened (file don't exist or in not valid), return NULL. +// Otherwise, the return value is a unzFile Handle, usable with other unzip functions +unzFile unzOpenInternal(LUFILE *fin) +{ if (fin==NULL) return NULL; + if (unz_copyright[0]!=' ') {lufclose(fin); return NULL;} + + int err=UNZ_OK; + unz_s us; + uLong central_pos,uL; + central_pos = unzlocal_SearchCentralDir(fin); + if (central_pos==0xFFFFFFFF) err=UNZ_ERRNO; + if (lufseek(fin,central_pos,SEEK_SET)!=0) err=UNZ_ERRNO; + // the signature, already checked + if (unzlocal_getLong(fin,&uL)!=UNZ_OK) err=UNZ_ERRNO; + // number of this disk + uLong number_disk; // number of the current dist, used for spanning ZIP, unsupported, always 0 + if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK) err=UNZ_ERRNO; + // number of the disk with the start of the central directory + uLong number_disk_with_CD; // number the the disk with central dir, used for spaning ZIP, unsupported, always 0 + if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO; + // total number of entries in the central dir on this disk + if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO; + // total number of entries in the central dir + uLong number_entry_CD; // total number of entries in the central dir (same than number_entry on nospan) + if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO; + if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE; + // size of the central directory + if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO; + // offset of start of central directory with respect to the starting disk number + if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO; + // zipfile comment length + if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO; + if ((central_pos+fin->initial_offsetinitial_offset - (us.offset_central_dir+us.size_central_dir); + us.central_pos = central_pos; + us.pfile_in_zip_read = NULL; + fin->initial_offset = 0; // since the zipfile itself is expected to handle this + + unz_s *s = (unz_s*)zmalloc(sizeof(unz_s)); + *s=us; + unzGoToFirstFile((unzFile)s); + return (unzFile)s; +} + + + +// Close a ZipFile opened with unzipOpen. +// If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), +// these files MUST be closed with unzipCloseCurrentFile before call unzipClose. +// return UNZ_OK if there is no problem. +int unzClose (unzFile file) +{ + unz_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + + if (s->pfile_in_zip_read!=NULL) + unzCloseCurrentFile(file); + + lufclose(s->file); + if (s) zfree(s); // unused s=0; + return UNZ_OK; +} + + +// Write info about the ZipFile in the *pglobal_info structure. +// No preparation of the structure is needed +// return UNZ_OK if there is no problem. +int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info) +{ + unz_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + *pglobal_info=s->gi; + return UNZ_OK; +} + + +// Translate date/time from Dos format to tm_unz (readable more easilty) +void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm) +{ + uLong uDate; + uDate = (uLong)(ulDosDate>>16); + ptm->tm_mday = (uInt)(uDate&0x1f) ; + ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; + ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; + + ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; + ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; +} + +// Get Info about the current file in the zipfile, with internal only info +int unzlocal_GetCurrentFileInfoInternal (unzFile file, + unz_file_info *pfile_info, + unz_file_info_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize); + +int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info, + unz_file_info_internal *pfile_info_internal, char *szFileName, + uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, + char *szComment, uLong commentBufferSize) +{ + unz_s* s; + unz_file_info file_info; + unz_file_info_internal file_info_internal; + int err=UNZ_OK; + uLong uMagic; + long lSeek=0; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + if (lufseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0) + err=UNZ_ERRNO; + + + // we check the magic + if (err==UNZ_OK) + if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x02014b50) + err=UNZ_BADZIPFILE; + + if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK) + err=UNZ_ERRNO; + + unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); + + if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK) + err=UNZ_ERRNO; + + lSeek+=file_info.size_filename; + if ((err==UNZ_OK) && (szFileName!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_filename0) && (fileNameBufferSize>0)) + if (lufread(szFileName,(uInt)uSizeRead,1,s->file)!=1) + err=UNZ_ERRNO; + lSeek -= uSizeRead; + } + + + if ((err==UNZ_OK) && (extraField!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_file_extrafile,lSeek,SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) + if (lufread(extraField,(uInt)uSizeRead,1,s->file)!=1) + err=UNZ_ERRNO; + lSeek += file_info.size_file_extra - uSizeRead; + } + else + lSeek+=file_info.size_file_extra; + + + if ((err==UNZ_OK) && (szComment!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_file_commentfile,lSeek,SEEK_CUR)==0) + {} // unused lSeek=0; + else + err=UNZ_ERRNO; + if ((file_info.size_file_comment>0) && (commentBufferSize>0)) + if (lufread(szComment,(uInt)uSizeRead,1,s->file)!=1) + err=UNZ_ERRNO; + //unused lSeek+=file_info.size_file_comment - uSizeRead; + } + else {} //unused lSeek+=file_info.size_file_comment; + + if ((err==UNZ_OK) && (pfile_info!=NULL)) + *pfile_info=file_info; + + if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) + *pfile_info_internal=file_info_internal; + + return err; +} + + + +// Write info about the ZipFile in the *pglobal_info structure. +// No preparation of the structure is needed +// return UNZ_OK if there is no problem. +int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info, + char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, + char *szComment, uLong commentBufferSize) +{ return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, szComment,commentBufferSize); +} + + +// Set the current file of the zipfile to the first file. +// return UNZ_OK if there is no problem +int unzGoToFirstFile (unzFile file) +{ + int err; + unz_s* s; + if (file==NULL) return UNZ_PARAMERROR; + s=(unz_s*)file; + s->pos_in_central_dir=s->offset_central_dir; + s->num_file=0; + err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + + +// Set the current file of the zipfile to the next file. +// return UNZ_OK if there is no problem +// return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +int unzGoToNextFile (unzFile file) +{ + unz_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + if (s->num_file+1==s->gi.number_entry) + return UNZ_END_OF_LIST_OF_FILE; + + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; + s->num_file++; + err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + + +// Try locate the file szFileName in the zipfile. +// For the iCaseSensitivity signification, see unzStringFileNameCompare +// return value : +// UNZ_OK if the file is found. It becomes the current file. +// UNZ_END_OF_LIST_OF_FILE if the file is not found +int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) +{ + unz_s* s; + int err; + + + uLong num_fileSaved; + uLong pos_in_central_dirSaved; + + + if (file==NULL) + return UNZ_PARAMERROR; + + if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) + return UNZ_PARAMERROR; + + s=(unz_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + num_fileSaved = s->num_file; + pos_in_central_dirSaved = s->pos_in_central_dir; + + err = unzGoToFirstFile(file); + + while (err == UNZ_OK) + { + char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; + unzGetCurrentFileInfo(file,NULL, + szCurrentFileName,sizeof(szCurrentFileName)-1, + NULL,0,NULL,0); + if (unzStringFileNameCompare(szCurrentFileName,szFileName,iCaseSensitivity)==0) + return UNZ_OK; + err = unzGoToNextFile(file); + } + + s->num_file = num_fileSaved ; + s->pos_in_central_dir = pos_in_central_dirSaved ; + return err; +} + + +// Read the local header of the current zipfile +// Check the coherency of the local header and info in the end of central +// directory about this file +// store in *piSizeVar the size of extra info in local header +// (filename and size of extra field data) +int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar, + uLong *poffset_local_extrafield, uInt *psize_local_extrafield) +{ + uLong uMagic,uData,uFlags; + uLong size_filename; + uLong size_extra_field; + int err=UNZ_OK; + + *piSizeVar = 0; + *poffset_local_extrafield = 0; + *psize_local_extrafield = 0; + + if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0) + return UNZ_ERRNO; + + + if (err==UNZ_OK) + if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x04034b50) + err=UNZ_BADZIPFILE; + + if (unzlocal_getShort(s->file,&uData) != UNZ_OK) + err=UNZ_ERRNO; +// else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) +// err=UNZ_BADZIPFILE; + if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK) + err=UNZ_ERRNO; + + if (unzlocal_getShort(s->file,&uData) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) + err=UNZ_BADZIPFILE; + + if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && + (s->cur_file_info.compression_method!=Z_DEFLATED)) + err=UNZ_BADZIPFILE; + + if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // date/time + err=UNZ_ERRNO; + + if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // crc + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && + ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size compr + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && + ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size uncompr + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && + ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + + if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) + err=UNZ_BADZIPFILE; + + *piSizeVar += (uInt)size_filename; + + if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK) + err=UNZ_ERRNO; + *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt)size_extra_field; + + *piSizeVar += (uInt)size_extra_field; + + return err; +} + + + + + +// Open for reading data the current file in the zipfile. +// If there is no error and the file is opened, the return value is UNZ_OK. +int unzOpenCurrentFile (unzFile file, const char *password) +{ + int err; + int Store; + uInt iSizeVar; + unz_s* s; + file_in_zip_read_info_s* pfile_in_zip_read_info; + uLong offset_local_extrafield; // offset of the local extra field + uInt size_local_extrafield; // size of the local extra field + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + if (!s->current_file_ok) + return UNZ_PARAMERROR; + + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); + + if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, + &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) + return UNZ_BADZIPFILE; + + pfile_in_zip_read_info = (file_in_zip_read_info_s*)zmalloc(sizeof(file_in_zip_read_info_s)); + if (pfile_in_zip_read_info==NULL) + return UNZ_INTERNALERROR; + + pfile_in_zip_read_info->read_buffer=(char*)zmalloc(UNZ_BUFSIZE); + pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; + pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; + pfile_in_zip_read_info->pos_local_extrafield=0; + + if (pfile_in_zip_read_info->read_buffer==NULL) + { + if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); //unused pfile_in_zip_read_info=0; + return UNZ_INTERNALERROR; + } + + pfile_in_zip_read_info->stream_initialised=0; + + if ((s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED)) + { // unused err=UNZ_BADZIPFILE; + } + Store = s->cur_file_info.compression_method==0; + + pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; + pfile_in_zip_read_info->crc32=0; + pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; + pfile_in_zip_read_info->file=s->file; + pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; + + pfile_in_zip_read_info->stream.total_out = 0; + + if (!Store) + { + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + + err=inflateInit2(&pfile_in_zip_read_info->stream); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=1; + // windowBits is passed < 0 to tell that there is no zlib header. + // Note that in this case inflate *requires* an extra "dummy" byte + // after the compressed stream in order to complete decompression and + // return Z_STREAM_END. + // In unzip, i don't wait absolutely Z_STREAM_END because I known the + // size of both compressed and uncompressed data + } + pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ; + pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ; + pfile_in_zip_read_info->encrypted = (s->cur_file_info.flag&1)!=0; + bool extlochead = (s->cur_file_info.flag&8)!=0; + if (extlochead) pfile_in_zip_read_info->crcenctest = (char)((s->cur_file_info.dosDate>>8)&0xff); + else pfile_in_zip_read_info->crcenctest = (char)(s->cur_file_info.crc >> 24); + pfile_in_zip_read_info->encheadleft = (pfile_in_zip_read_info->encrypted?12:0); + pfile_in_zip_read_info->keys[0] = 305419896L; + pfile_in_zip_read_info->keys[1] = 591751049L; + pfile_in_zip_read_info->keys[2] = 878082192L; + for (const char *cp=password; cp!=0 && *cp!=0; cp++) Uupdate_keys(pfile_in_zip_read_info->keys,*cp); + + pfile_in_zip_read_info->pos_in_zipfile = + s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + + iSizeVar; + + pfile_in_zip_read_info->stream.avail_in = (uInt)0; + + s->pfile_in_zip_read = pfile_in_zip_read_info; + + return UNZ_OK; +} + + +// Read bytes from the current file. +// buf contain buffer where data must be copied +// len the size of buf. +// return the number of byte copied if somes bytes are copied (and also sets *reached_eof) +// return 0 if the end of file was reached. (and also sets *reached_eof). +// return <0 with error code if there is an error. (in which case *reached_eof is meaningless) +// (UNZ_ERRNO for IO error, or zLib error for uncompress error) +int unzReadCurrentFile (unzFile file, voidp buf, unsigned len, bool *reached_eof) +{ int err=UNZ_OK; + uInt iRead = 0; + if (reached_eof!=0) *reached_eof=false; + + unz_s *s = (unz_s*)file; + if (s==NULL) return UNZ_PARAMERROR; + + file_in_zip_read_info_s* pfile_in_zip_read_info = s->pfile_in_zip_read; + if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; + if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE; + if (len==0) return 0; + + pfile_in_zip_read_info->stream.next_out = (Byte*)buf; + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + + if (len>pfile_in_zip_read_info->rest_read_uncompressed) + { pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed; + } + + while (pfile_in_zip_read_info->stream.avail_out>0) + { if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0)) + { uInt uReadThis = UNZ_BUFSIZE; + if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; + if (uReadThis == 0) {if (reached_eof!=0) *reached_eof=true; return UNZ_EOF;} + if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0) return UNZ_ERRNO; + if (lufread(pfile_in_zip_read_info->read_buffer,uReadThis,1,pfile_in_zip_read_info->file)!=1) return UNZ_ERRNO; + pfile_in_zip_read_info->pos_in_zipfile += uReadThis; + pfile_in_zip_read_info->rest_read_compressed-=uReadThis; + pfile_in_zip_read_info->stream.next_in = (Byte*)pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; + // + if (pfile_in_zip_read_info->encrypted) + { char *buf = (char*)pfile_in_zip_read_info->stream.next_in; + for (unsigned int i=0; ikeys,buf[i]); + } + } + + unsigned int uDoEncHead = pfile_in_zip_read_info->encheadleft; + if (uDoEncHead>pfile_in_zip_read_info->stream.avail_in) uDoEncHead=pfile_in_zip_read_info->stream.avail_in; + if (uDoEncHead>0) + { char bufcrc=pfile_in_zip_read_info->stream.next_in[uDoEncHead-1]; + //pfile_in_zip_read_info->rest_read_uncompressed-=uDoEncHead; // commented by ROTA + pfile_in_zip_read_info->stream.avail_in -= uDoEncHead; + pfile_in_zip_read_info->stream.next_in += uDoEncHead; + pfile_in_zip_read_info->encheadleft -= uDoEncHead; + if (pfile_in_zip_read_info->encheadleft==0) + { if (bufcrc!=pfile_in_zip_read_info->crcenctest) return UNZ_PASSWORD; + } + } + + if (pfile_in_zip_read_info->compression_method==0) + { uInt uDoCopy,i ; + if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in) + { uDoCopy = pfile_in_zip_read_info->stream.avail_out ; + } + else + { uDoCopy = pfile_in_zip_read_info->stream.avail_in ; + } + for (i=0;istream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i); + pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,pfile_in_zip_read_info->stream.next_out,uDoCopy); + pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; + pfile_in_zip_read_info->stream.avail_in -= uDoCopy; + pfile_in_zip_read_info->stream.avail_out -= uDoCopy; + pfile_in_zip_read_info->stream.next_out += uDoCopy; + pfile_in_zip_read_info->stream.next_in += uDoCopy; + pfile_in_zip_read_info->stream.total_out += uDoCopy; + iRead += uDoCopy; + if (pfile_in_zip_read_info->rest_read_uncompressed==0) {if (reached_eof!=0) *reached_eof=true;} + } + else + { uLong uTotalOutBefore,uTotalOutAfter; + const Byte *bufBefore; + uLong uOutThis; + int flush=Z_SYNC_FLUSH; + uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; + bufBefore = pfile_in_zip_read_info->stream.next_out; + // + err=inflate(&pfile_in_zip_read_info->stream,flush); + // + uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; + uOutThis = uTotalOutAfter-uTotalOutBefore; + pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,bufBefore,(uInt)(uOutThis)); + pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + if (err==Z_STREAM_END || pfile_in_zip_read_info->rest_read_uncompressed==0) + { if (reached_eof!=0) *reached_eof=true; + return iRead; + } + if (err!=Z_OK) break; + } + } + + if (err==Z_OK) return iRead; + return err; +} + + +// Give the current position in uncompressed data +z_off_t unztell (unzFile file) +{ + unz_s* s; + file_in_zip_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + return (z_off_t)pfile_in_zip_read_info->stream.total_out; +} + + +// return 1 if the end of file was reached, 0 elsewhere +int unzeof (unzFile file) +{ + unz_s* s; + file_in_zip_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + return 1; + else + return 0; +} + + + +// Read extra field from the current file (opened by unzOpenCurrentFile) +// This is the local-header version of the extra field (sometimes, there is +// more info in the local-header version than in the central-header) +// if buf==NULL, it return the size of the local extra field that can be read +// if buf!=NULL, len is the size of the buffer, the extra header is copied in buf. +// the return value is the number of bytes copied in buf, or (if <0) the error code +int unzGetLocalExtrafield (unzFile file,voidp buf,unsigned len) +{ + unz_s* s; + file_in_zip_read_info_s* pfile_in_zip_read_info; + uInt read_now; + uLong size_to_read; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - + pfile_in_zip_read_info->pos_local_extrafield); + + if (buf==NULL) + return (int)size_to_read; + + if (len>size_to_read) + read_now = (uInt)size_to_read; + else + read_now = (uInt)len ; + + if (read_now==0) + return 0; + + if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0) + return UNZ_ERRNO; + + if (lufread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1) + return UNZ_ERRNO; + + return (int)read_now; +} + +// Close the file in zip opened with unzipOpenCurrentFile +// Return UNZ_CRCERROR if all the file was read but the CRC is not good +int unzCloseCurrentFile (unzFile file) +{ + int err=UNZ_OK; + + unz_s* s; + file_in_zip_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + { + if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) + err=UNZ_CRCERROR; + } + + + if (pfile_in_zip_read_info->read_buffer!=0) + { void *buf = pfile_in_zip_read_info->read_buffer; + zfree(buf); + pfile_in_zip_read_info->read_buffer=0; + } + pfile_in_zip_read_info->read_buffer = NULL; + if (pfile_in_zip_read_info->stream_initialised) + inflateEnd(&pfile_in_zip_read_info->stream); + + pfile_in_zip_read_info->stream_initialised = 0; + if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); // unused pfile_in_zip_read_info=0; + + s->pfile_in_zip_read=NULL; + + return err; +} + + +// Get the global comment string of the ZipFile, in the szComment buffer. +// uSizeBuf is the size of the szComment buffer. +// return the number of byte copied or an error code <0 +int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf) +{ //int err=UNZ_OK; + unz_s* s; + uLong uReadThis ; + if (file==NULL) return UNZ_PARAMERROR; + s=(unz_s*)file; + uReadThis = uSizeBuf; + if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment; + if (lufseek(s->file,s->central_pos+22,SEEK_SET)!=0) return UNZ_ERRNO; + if (uReadThis>0) + { *szComment='\0'; + if (lufread(szComment,(uInt)uReadThis,1,s->file)!=1) return UNZ_ERRNO; + } + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0'; + return (int)uReadThis; +} + + + + + +int unzOpenCurrentFile (unzFile file, const char *password); +int unzReadCurrentFile (unzFile file, void *buf, unsigned len); +int unzCloseCurrentFile (unzFile file); + + +typedef unsigned __int32 lutime_t; // define it ourselves since we don't include time.h + +FILETIME timet2filetime(const lutime_t t) +{ LONGLONG i = Int32x32To64(t,10000000) + 116444736000000000; + FILETIME ft; + ft.dwLowDateTime = (DWORD) i; + ft.dwHighDateTime = (DWORD)(i >>32); + return ft; +} + +FILETIME dosdatetime2filetime(WORD dosdate,WORD dostime) +{ // date: bits 0-4 are day of month 1-31. Bits 5-8 are month 1..12. Bits 9-15 are year-1980 + // time: bits 0-4 are seconds/2, bits 5-10 are minute 0..59. Bits 11-15 are hour 0..23 + SYSTEMTIME st; + st.wYear = (WORD)(((dosdate>>9)&0x7f) + 1980); + st.wMonth = (WORD)((dosdate>>5)&0xf); + st.wDay = (WORD)(dosdate&0x1f); + st.wHour = (WORD)((dostime>>11)&0x1f); + st.wMinute = (WORD)((dostime>>5)&0x3f); + st.wSecond = (WORD)((dostime&0x1f)*2); + st.wMilliseconds = 0; + FILETIME ft; SystemTimeToFileTime(&st,&ft); + return ft; +} + + + +class TUnzip +{ public: + TUnzip(const char *pwd) : uf(0), unzbuf(0), currentfile(-1), czei(-1), password(0) {if (pwd!=0) {password=new char[strlen(pwd)+1]; strcpy(password,pwd);}} + ~TUnzip() {if (password!=0) delete[] password; password=0; if (unzbuf!=0) delete[] unzbuf; unzbuf=0;} + + unzFile uf; int currentfile; ZIPENTRY cze; int czei; + char *password; + char *unzbuf; // lazily created and destroyed, used by Unzip + TCHAR rootdir[MAX_PATH]; // includes a trailing slash + + ZRESULT Open(void *z,unsigned int len,DWORD flags); + ZRESULT Get(int index,ZIPENTRY *ze); + ZRESULT Find(const TCHAR *name,bool ic,int *index,ZIPENTRY *ze); + ZRESULT Unzip(int index,void *dst,unsigned int len,DWORD flags); + ZRESULT SetUnzipBaseDir(const TCHAR *dir); + ZRESULT Close(); +}; + + +ZRESULT TUnzip::Open(void *z,unsigned int len,DWORD flags) +{ if (uf!=0 || currentfile!=-1) return ZR_NOTINITED; + // +#ifdef GetCurrentDirectory + GetCurrentDirectory(MAX_PATH,rootdir); +#else + _tcscpy(rootdir,_T("\\")); +#endif + TCHAR lastchar = rootdir[_tcslen(rootdir)-1]; + if (lastchar!='\\' && lastchar!='/') _tcscat(rootdir,_T("\\")); + // + if (flags==ZIP_HANDLE) + { // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE. + DWORD res = SetFilePointer(z,0,0,FILE_CURRENT); + bool canseek = (res!=0xFFFFFFFF); + if (!canseek) return ZR_SEEK; + } + ZRESULT e; LUFILE *f = lufopen(z,len,flags,&e); + if (f==NULL) return e; + uf = unzOpenInternal(f); + if (uf==0) return ZR_NOFILE; + return ZR_OK; +} + +ZRESULT TUnzip::SetUnzipBaseDir(const TCHAR *dir) +{ _tcscpy(rootdir,dir); + TCHAR lastchar = rootdir[_tcslen(rootdir)-1]; + if (lastchar!='\\' && lastchar!='/') _tcscat(rootdir,_T("\\")); + return ZR_OK; +} + +ZRESULT TUnzip::Get(int index,ZIPENTRY *ze) +{ if (index<-1 || index>=(int)uf->gi.number_entry) return ZR_ARGS; + if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; + if (index==czei && index!=-1) {memcpy(ze,&cze,sizeof(ZIPENTRY)); return ZR_OK;} + if (index==-1) + { ze->index = uf->gi.number_entry; + ze->name[0]=0; + ze->attr=0; + ze->atime.dwLowDateTime=0; ze->atime.dwHighDateTime=0; + ze->ctime.dwLowDateTime=0; ze->ctime.dwHighDateTime=0; + ze->mtime.dwLowDateTime=0; ze->mtime.dwHighDateTime=0; + ze->comp_size=0; + ze->unc_size=0; + return ZR_OK; + } + if (index<(int)uf->num_file) unzGoToFirstFile(uf); + while ((int)uf->num_filefile,offset,SEEK_SET)!=0) return ZR_READ; + unsigned char *extra = new unsigned char[extralen]; + if (lufread(extra,1,(uInt)extralen,uf->file)!=extralen) {delete[] extra; return ZR_READ;} + // + ze->index=uf->num_file; + TCHAR tfn[MAX_PATH]; +#ifdef UNICODE + MultiByteToWideChar(CP_UTF8,0,fn,-1,tfn,MAX_PATH); +#else + strcpy(tfn,fn); +#endif + // As a safety feature: if the zip filename had sneaky stuff + // like "c:\windows\file.txt" or "\windows\file.txt" or "fred\..\..\..\windows\file.txt" + // then we get rid of them all. That way, when the programmer does UnzipItem(hz,i,ze.name), + // it won't be a problem. (If the programmer really did want to get the full evil information, + // then they can edit out this security feature from here). + // In particular, we chop off any prefixes that are "c:\" or "\" or "/" or "[stuff]\.." or "[stuff]/.." + const TCHAR *sfn=tfn; + for (;;) + { if (sfn[0]!=0 && sfn[1]==':') {sfn+=2; continue;} + if (sfn[0]=='\\') {sfn++; continue;} + if (sfn[0]=='/') {sfn++; continue;} + const TCHAR *c; + c=_tcsstr(sfn,_T("\\..\\")); if (c!=0) {sfn=c+4; continue;} + c=_tcsstr(sfn,_T("\\../")); if (c!=0) {sfn=c+4; continue;} + c=_tcsstr(sfn,_T("/../")); if (c!=0) {sfn=c+4; continue;} + c=_tcsstr(sfn,_T("/..\\")); if (c!=0) {sfn=c+4; continue;} + break; + } + _tcscpy(ze->name, sfn); + + + // zip has an 'attribute' 32bit value. Its lower half is windows stuff + // its upper half is standard unix stat.st_mode. We'll start trying + // to read it in unix mode + unsigned long a = ufi.external_fa; + bool isdir = (a&0x40000000)!=0; + bool readonly= (a&0x00800000)==0; + //bool readable= (a&0x01000000)!=0; // unused + //bool executable=(a&0x00400000)!=0; // unused + bool hidden=false, system=false, archive=true; + // but in normal hostmodes these are overridden by the lower half... + int host = ufi.version>>8; + if (host==0 || host==7 || host==11 || host==14) + { readonly= (a&0x00000001)!=0; + hidden= (a&0x00000002)!=0; + system= (a&0x00000004)!=0; + isdir= (a&0x00000010)!=0; + archive= (a&0x00000020)!=0; + } + ze->attr=0; + if (isdir) ze->attr |= FILE_ATTRIBUTE_DIRECTORY; + if (archive) ze->attr|=FILE_ATTRIBUTE_ARCHIVE; + if (hidden) ze->attr|=FILE_ATTRIBUTE_HIDDEN; + if (readonly) ze->attr|=FILE_ATTRIBUTE_READONLY; + if (system) ze->attr|=FILE_ATTRIBUTE_SYSTEM; + ze->comp_size = ufi.compressed_size; + ze->unc_size = ufi.uncompressed_size; + // + WORD dostime = (WORD)(ufi.dosDate&0xFFFF); + WORD dosdate = (WORD)((ufi.dosDate>>16)&0xFFFF); + FILETIME ftd = dosdatetime2filetime(dosdate,dostime); + FILETIME ft; LocalFileTimeToFileTime(&ftd,&ft); + ze->atime=ft; ze->ctime=ft; ze->mtime=ft; + // the zip will always have at least that dostime. But if it also has + // an extra header, then we'll instead get the info from that. + unsigned int epos=0; + while (epos+4mtime = timet2filetime(mtime); + } + if (hasatime) + { lutime_t atime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24); + epos+=4; + ze->atime = timet2filetime(atime); + } + if (hasctime) + { lutime_t ctime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24); + epos+=4; + ze->ctime = timet2filetime(ctime); + } + break; + } + // + if (extra!=0) delete[] extra; + memcpy(&cze,ze,sizeof(ZIPENTRY)); czei=index; + return ZR_OK; +} + +ZRESULT TUnzip::Find(const TCHAR *tname,bool ic,int *index,ZIPENTRY *ze) +{ char name[MAX_PATH]; +#ifdef UNICODE + WideCharToMultiByte(CP_UTF8,0,tname,-1,name,MAX_PATH,0,0); +#else + strcpy(name,tname); +#endif + int res = unzLocateFile(uf,name,ic?CASE_INSENSITIVE:CASE_SENSITIVE); + if (res!=UNZ_OK) + { if (index!=0) *index=-1; + if (ze!=NULL) {ZeroMemory(ze,sizeof(ZIPENTRY)); ze->index=-1;} + return ZR_NOTFOUND; + } + if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; + int i = (int)uf->num_file; + if (index!=NULL) *index=i; + if (ze!=NULL) + { ZRESULT zres = Get(i,ze); + if (zres!=ZR_OK) return zres; + } + return ZR_OK; +} + +void EnsureDirectory(const TCHAR *rootdir, const TCHAR *dir) +{ if (rootdir!=0 && GetFileAttributes(rootdir)==0xFFFFFFFF) CreateDirectory(rootdir,0); + if (*dir==0) return; + const TCHAR *lastslash=dir, *c=lastslash; + while (*c!=0) {if (*c=='/' || *c=='\\') lastslash=c; c++;} + const TCHAR *name=lastslash; + if (lastslash!=dir) + { TCHAR tmp[MAX_PATH]; memcpy(tmp,dir,sizeof(TCHAR)*(lastslash-dir)); + tmp[lastslash-dir]=0; + EnsureDirectory(rootdir,tmp); + name++; + } + TCHAR cd[MAX_PATH]; *cd=0; if (rootdir!=0) _tcscpy(cd,rootdir); _tcscat(cd,dir); + if (GetFileAttributes(cd)==0xFFFFFFFF) CreateDirectory(cd,NULL); +} + + + +ZRESULT TUnzip::Unzip(int index,void *dst,unsigned int len,DWORD flags) +{ if (flags!=ZIP_MEMORY && flags!=ZIP_FILENAME && flags!=ZIP_HANDLE) return ZR_ARGS; + if (flags==ZIP_MEMORY) + { if (index!=currentfile) + { if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; + if (index>=(int)uf->gi.number_entry) return ZR_ARGS; + if (index<(int)uf->num_file) unzGoToFirstFile(uf); + while ((int)uf->num_file0) return ZR_MORE; + if (res==UNZ_PASSWORD) return ZR_PASSWORD; + return ZR_FLATE; + } + // otherwise we're writing to a handle or a file + if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; + if (index>=(int)uf->gi.number_entry) return ZR_ARGS; + if (index<(int)uf->num_file) unzGoToFirstFile(uf); + while ((int)uf->num_file0) {DWORD writ; BOOL bres=WriteFile(h,unzbuf,res,&writ,NULL); if (!bres) {haderr=ZR_WRITE; break;}} + if (reached_eof) break; + if (res==0) {haderr=ZR_FLATE; break;} + } + if (!haderr) SetFileTime(h,&ze.ctime,&ze.atime,&ze.mtime); // may fail if it was a pipe + if (flags!=ZIP_HANDLE) CloseHandle(h); + unzCloseCurrentFile(uf); + if (haderr!=0) return haderr; + return ZR_OK; +} + +ZRESULT TUnzip::Close() +{ if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; + if (uf!=0) unzClose(uf); uf=0; + return ZR_OK; +} + + + + + +ZRESULT lasterrorU=ZR_OK; + +unsigned int FormatZipMessageU(ZRESULT code, TCHAR *buf,unsigned int len) +{ if (code==ZR_RECENT) code=lasterrorU; + const TCHAR *msg=_T("unknown zip result code"); + switch (code) + { case ZR_OK: msg=_T("Success"); break; + case ZR_NODUPH: msg=_T("Culdn't duplicate handle"); break; + case ZR_NOFILE: msg=_T("Couldn't create/open file"); break; + case ZR_NOALLOC: msg=_T("Failed to allocate memory"); break; + case ZR_WRITE: msg=_T("Error writing to file"); break; + case ZR_NOTFOUND: msg=_T("File not found in the zipfile"); break; + case ZR_MORE: msg=_T("Still more data to unzip"); break; + case ZR_CORRUPT: msg=_T("Zipfile is corrupt or not a zipfile"); break; + case ZR_READ: msg=_T("Error reading file"); break; + case ZR_PASSWORD: msg=_T("Correct password required"); break; + case ZR_ARGS: msg=_T("Caller: faulty arguments"); break; + case ZR_PARTIALUNZ: msg=_T("Caller: the file had already been partially unzipped"); break; + case ZR_NOTMMAP: msg=_T("Caller: can only get memory of a memory zipfile"); break; + case ZR_MEMSIZE: msg=_T("Caller: not enough space allocated for memory zipfile"); break; + case ZR_FAILED: msg=_T("Caller: there was a previous error"); break; + case ZR_ENDED: msg=_T("Caller: additions to the zip have already been ended"); break; + case ZR_ZMODE: msg=_T("Caller: mixing creation and opening of zip"); break; + case ZR_NOTINITED: msg=_T("Zip-bug: internal initialisation not completed"); break; + case ZR_SEEK: msg=_T("Zip-bug: trying to seek the unseekable"); break; + case ZR_MISSIZE: msg=_T("Zip-bug: the anticipated size turned out wrong"); break; + case ZR_NOCHANGE: msg=_T("Zip-bug: tried to change mind, but not allowed"); break; + case ZR_FLATE: msg=_T("Zip-bug: an internal error during flation"); break; + } + unsigned int mlen=(unsigned int)_tcslen(msg); + if (buf==0 || len==0) return mlen; + unsigned int n=mlen; if (n+1>len) n=len-1; + _tcsncpy(buf,msg,n); buf[n]=0; + return mlen; +} + + +typedef struct +{ DWORD flag; + TUnzip *unz; +} TUnzipHandleData; + +HZIP OpenZipInternal(void *z,unsigned int len,DWORD flags, const char *password) +{ TUnzip *unz = new TUnzip(password); + lasterrorU = unz->Open(z,len,flags); + if (lasterrorU!=ZR_OK) {delete unz; return 0;} + TUnzipHandleData *han = new TUnzipHandleData; + han->flag=1; han->unz=unz; return (HZIP)han; +} +HZIP OpenZipHandle(HANDLE h, const char *password) {return OpenZipInternal((void*)h,0,ZIP_HANDLE,password);} +HZIP OpenZip(const TCHAR *fn, const char *password) {return OpenZipInternal((void*)fn,0,ZIP_FILENAME,password);} +HZIP OpenZip(void *z,unsigned int len, const char *password) {return OpenZipInternal(z,len,ZIP_MEMORY,password);} + + +ZRESULT GetZipItem(HZIP hz, int index, ZIPENTRY *ze) +{ ze->index=0; *ze->name=0; ze->unc_size=0; + if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} + TUnzipHandleData *han = (TUnzipHandleData*)hz; + if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} + TUnzip *unz = han->unz; + lasterrorU = unz->Get(index,ze); + return lasterrorU; +} + +ZRESULT FindZipItem(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze) +{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} + TUnzipHandleData *han = (TUnzipHandleData*)hz; + if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} + TUnzip *unz = han->unz; + lasterrorU = unz->Find(name,ic,index,ze); + return lasterrorU; +} + +ZRESULT UnzipItemInternal(HZIP hz, int index, void *dst, unsigned int len, DWORD flags) +{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} + TUnzipHandleData *han = (TUnzipHandleData*)hz; + if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} + TUnzip *unz = han->unz; + lasterrorU = unz->Unzip(index,dst,len,flags); + return lasterrorU; +} +ZRESULT UnzipItemHandle(HZIP hz, int index, HANDLE h) {return UnzipItemInternal(hz,index,(void*)h,0,ZIP_HANDLE);} +ZRESULT UnzipItem(HZIP hz, int index, const TCHAR *fn) {return UnzipItemInternal(hz,index,(void*)fn,0,ZIP_FILENAME);} +ZRESULT UnzipItem(HZIP hz, int index, void *z,unsigned int len) {return UnzipItemInternal(hz,index,z,len,ZIP_MEMORY);} + +ZRESULT SetUnzipBaseDir(HZIP hz, const TCHAR *dir) +{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} + TUnzipHandleData *han = (TUnzipHandleData*)hz; + if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} + TUnzip *unz = han->unz; + lasterrorU = unz->SetUnzipBaseDir(dir); + return lasterrorU; +} + + +ZRESULT CloseZipU(HZIP hz) +{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} + TUnzipHandleData *han = (TUnzipHandleData*)hz; + if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} + TUnzip *unz = han->unz; + lasterrorU = unz->Close(); + delete unz; + delete han; + return lasterrorU; +} + +bool IsZipHandleU(HZIP hz) +{ if (hz==0) return false; + TUnzipHandleData *han = (TUnzipHandleData*)hz; + return (han->flag==1); +} + + diff --git a/uMod2/uMod_GUI/unzip.h b/uMod2/uMod_GUI/unzip.h new file mode 100644 index 0000000..d87d771 --- /dev/null +++ b/uMod2/uMod_GUI/unzip.h @@ -0,0 +1,214 @@ +#ifndef _unzip_H +#define _unzip_H +//#define TCHAR char +// UNZIPPING functions -- for unzipping. +// This file is a repackaged form of extracts from the zlib code available +// at www.gzip.org/zlib, by Jean-Loup Gailly and Mark Adler. The original +// copyright notice may be found in unzip.cpp. The repackaging was done +// by Lucian Wischik to simplify and extend its use in Windows/C++. Also +// encryption and unicode filenames have been added. + + +#ifndef _zip_H +DECLARE_HANDLE(HZIP); +#endif +// An HZIP identifies a zip file that has been opened + +typedef DWORD ZRESULT; +// return codes from any of the zip functions. Listed later. + +typedef struct +{ int index; // index of this file within the zip + TCHAR name[MAX_PATH]; // filename within the zip + DWORD attr; // attributes, as in GetFileAttributes. + FILETIME atime,ctime,mtime;// access, create, modify filetimes + long comp_size; // sizes of item, compressed and uncompressed. These + long unc_size; // may be -1 if not yet known (e.g. being streamed in) +} ZIPENTRY; + + +HZIP OpenZip(const TCHAR *fn, const char *password); +HZIP OpenZip(void *z,unsigned int len, const char *password); +HZIP OpenZipHandle(HANDLE h, const char *password); +// OpenZip - opens a zip file and returns a handle with which you can +// subsequently examine its contents. You can open a zip file from: +// from a pipe: OpenZipHandle(hpipe_read,0); +// from a file (by handle): OpenZipHandle(hfile,0); +// from a file (by name): OpenZip("c:\\test.zip","password"); +// from a memory block: OpenZip(bufstart, buflen,0); +// If the file is opened through a pipe, then items may only be +// accessed in increasing order, and an item may only be unzipped once, +// although GetZipItem can be called immediately before and after unzipping +// it. If it's opened in any other way, then full random access is possible. +// Note: pipe input is not yet implemented. +// Note: zip passwords are ascii, not unicode. +// Note: for windows-ce, you cannot close the handle until after CloseZip. +// but for real windows, the zip makes its own copy of your handle, so you +// can close yours anytime. + +ZRESULT GetZipItem(HZIP hz, int index, ZIPENTRY *ze); +// GetZipItem - call this to get information about an item in the zip. +// If index is -1 and the file wasn't opened through a pipe, +// then it returns information about the whole zipfile +// (and in particular ze.index returns the number of index items). +// Note: the item might be a directory (ze.attr & FILE_ATTRIBUTE_DIRECTORY) +// See below for notes on what happens when you unzip such an item. +// Note: if you are opening the zip through a pipe, then random access +// is not possible and GetZipItem(-1) fails and you can't discover the number +// of items except by calling GetZipItem on each one of them in turn, +// starting at 0, until eventually the call fails. Also, in the event that +// you are opening through a pipe and the zip was itself created into a pipe, +// then then comp_size and sometimes unc_size as well may not be known until +// after the item has been unzipped. + +ZRESULT FindZipItem(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze); +// FindZipItem - finds an item by name. ic means 'insensitive to case'. +// It returns the index of the item, and returns information about it. +// If nothing was found, then index is set to -1 and the function returns +// an error code. + +ZRESULT UnzipItem(HZIP hz, int index, const TCHAR *fn); +ZRESULT UnzipItem(HZIP hz, int index, void *z,unsigned int len); +ZRESULT UnzipItemHandle(HZIP hz, int index, HANDLE h); +// UnzipItem - given an index to an item, unzips it. You can unzip to: +// to a pipe: UnzipItemHandle(hz,i, hpipe_write); +// to a file (by handle): UnzipItemHandle(hz,i, hfile); +// to a file (by name): UnzipItem(hz,i, ze.name); +// to a memory block: UnzipItem(hz,i, buf,buflen); +// In the final case, if the buffer isn't large enough to hold it all, +// then the return code indicates that more is yet to come. If it was +// large enough, and you want to know precisely how big, GetZipItem. +// Note: zip files are normally stored with relative pathnames. If you +// unzip with ZIP_FILENAME a relative pathname then the item gets created +// relative to the current directory - it first ensures that all necessary +// subdirectories have been created. Also, the item may itself be a directory. +// If you unzip a directory with ZIP_FILENAME, then the directory gets created. +// If you unzip it to a handle or a memory block, then nothing gets created +// and it emits 0 bytes. +ZRESULT SetUnzipBaseDir(HZIP hz, const TCHAR *dir); +// if unzipping to a filename, and it's a relative filename, then it will be relative to here. +// (defaults to current-directory). + + +ZRESULT CloseZip(HZIP hz); +// CloseZip - the zip handle must be closed with this function. + +unsigned int FormatZipMessage(ZRESULT code, TCHAR *buf,unsigned int len); +// FormatZipMessage - given an error code, formats it as a string. +// It returns the length of the error message. If buf/len points +// to a real buffer, then it also writes as much as possible into there. + + +// These are the result codes: +#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned, +#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage. +// The following come from general system stuff (e.g. files not openable) +#define ZR_GENMASK 0x0000FF00 +#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle +#define ZR_NOFILE 0x00000200 // couldn't create/open the file +#define ZR_NOALLOC 0x00000300 // failed to allocate some resource +#define ZR_WRITE 0x00000400 // a general error writing to the file +#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip +#define ZR_MORE 0x00000600 // there's still more data to be unzipped +#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile +#define ZR_READ 0x00000800 // a general error reading the file +#define ZR_PASSWORD 0x00001000 // we didn't get the right password to unzip the file +// The following come from mistakes on the part of the caller +#define ZR_CALLERMASK 0x00FF0000 +#define ZR_ARGS 0x00010000 // general mistake with the arguments +#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't +#define ZR_MEMSIZE 0x00030000 // the memory size is too small +#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function +#define ZR_ENDED 0x00050000 // the zip creation has already been closed +#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken +#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped +#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip +// The following come from bugs within the zip library itself +#define ZR_BUGMASK 0xFF000000 +#define ZR_NOTINITED 0x01000000 // initialisation didn't work +#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file +#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed +#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code + + + + + +// e.g. +// +// SetCurrentDirectory("c:\\docs\\stuff"); +// HZIP hz = OpenZip("c:\\stuff.zip",0); +// ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index; +// for (int i=0; i +#include +#include +#include "zip.h" + + +// THIS FILE is almost entirely based upon code by info-zip. +// It has been modified by Lucian Wischik. The modifications +// were a complete rewrite of the bit of code that generates the +// layout of the zipfile, and support for zipping to/from memory +// or handles or pipes or pagefile or diskfiles, encryption, unicode. +// The original code may be found at http://www.info-zip.org +// The original copyright text follows. +// +// +// +// This is version 1999-Oct-05 of the Info-ZIP copyright and license. +// The definitive version of this document should be available at +// ftp://ftp.cdrom.com/pub/infozip/license.html indefinitely. +// +// Copyright (c) 1990-1999 Info-ZIP. All rights reserved. +// +// For the purposes of this copyright and license, "Info-ZIP" is defined as +// the following set of individuals: +// +// Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois, +// Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase, +// Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz, David Kirschbaum, +// Johnny Lee, Onno van der Linden, Igor Mandrichenko, Steve P. Miller, +// Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs, Kai Uwe Rommel, +// Steve Salisbury, Dave Smith, Christian Spieler, Antoine Verheijen, +// Paul von Behren, Rich Wales, Mike White +// +// This software is provided "as is," without warranty of any kind, express +// or implied. In no event shall Info-ZIP or its contributors be held liable +// for any direct, indirect, incidental, special or consequential damages +// arising out of the use of or inability to use this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. Redistributions of source code must retain the above copyright notice, +// definition, disclaimer, and this list of conditions. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, definition, disclaimer, and this list of conditions in +// documentation and/or other materials provided with the distribution. +// +// 3. Altered versions--including, but not limited to, ports to new operating +// systems, existing ports with new graphical interfaces, and dynamic, +// shared, or static library versions--must be plainly marked as such +// and must not be misrepresented as being the original source. Such +// altered versions also must not be misrepresented as being Info-ZIP +// releases--including, but not limited to, labeling of the altered +// versions with the names "Info-ZIP" (or any variation thereof, including, +// but not limited to, different capitalizations), "Pocket UnZip," "WiZ" +// or "MacZip" without the explicit permission of Info-ZIP. Such altered +// versions are further prohibited from misrepresentative use of the +// Zip-Bugs or Info-ZIP e-mail addresses or of the Info-ZIP URL(s). +// +// 4. Info-ZIP retains the right to use the names "Info-ZIP," "Zip," "UnZip," +// "WiZ," "Pocket UnZip," "Pocket Zip," and "MacZip" for its own source and +// binary releases. +// + + +typedef unsigned char uch; // unsigned 8-bit value +typedef unsigned short ush; // unsigned 16-bit value +typedef unsigned long ulg; // unsigned 32-bit value +typedef size_t extent; // file size +typedef unsigned Pos; // must be at least 32 bits +typedef unsigned IPos; // A Pos is an index in the character window. Pos is used only for parameter passing + +#ifndef EOF +#define EOF (-1) +#endif + + +// Error return values. The values 0..4 and 12..18 follow the conventions +// of PKZIP. The values 4..10 are all assigned to "insufficient memory" +// by PKZIP, so the codes 5..10 are used here for other purposes. +#define ZE_MISS -1 // used by procname(), zipbare() +#define ZE_OK 0 // success +#define ZE_EOF 2 // unexpected end of zip file +#define ZE_FORM 3 // zip file structure error +#define ZE_MEM 4 // out of memory +#define ZE_LOGIC 5 // internal logic error +#define ZE_BIG 6 // entry too large to split +#define ZE_NOTE 7 // invalid comment format +#define ZE_TEST 8 // zip test (-T) failed or out of memory +#define ZE_ABORT 9 // user interrupt or termination +#define ZE_TEMP 10 // error using a temp file +#define ZE_READ 11 // read or seek error +#define ZE_NONE 12 // nothing to do +#define ZE_NAME 13 // missing or empty zip file +#define ZE_WRITE 14 // error writing to a file +#define ZE_CREAT 15 // couldn't open to write +#define ZE_PARMS 16 // bad command line +#define ZE_OPEN 18 // could not open a specified file to read +#define ZE_MAXERR 18 // the highest error number + + +// internal file attribute +#define UNKNOWN (-1) +#define BINARY 0 +#define ASCII 1 + +#define BEST -1 // Use best method (deflation or store) +#define STORE 0 // Store method +#define DEFLATE 8 // Deflation method + +#define CRCVAL_INITIAL 0L + +// MSDOS file or directory attributes +#define MSDOS_HIDDEN_ATTR 0x02 +#define MSDOS_DIR_ATTR 0x10 + +// Lengths of headers after signatures in bytes +#define LOCHEAD 26 +#define CENHEAD 42 +#define ENDHEAD 18 + +// Definitions for extra field handling: +#define EB_HEADSIZE 4 /* length of a extra field block header */ +#define EB_LEN 2 /* offset of data length field in header */ +#define EB_UT_MINLEN 1 /* minimal UT field contains Flags byte */ +#define EB_UT_FLAGS 0 /* byte offset of Flags field */ +#define EB_UT_TIME1 1 /* byte offset of 1st time value */ +#define EB_UT_FL_MTIME (1 << 0) /* mtime present */ +#define EB_UT_FL_ATIME (1 << 1) /* atime present */ +#define EB_UT_FL_CTIME (1 << 2) /* ctime present */ +#define EB_UT_LEN(n) (EB_UT_MINLEN + 4 * (n)) +#define EB_L_UT_SIZE (EB_HEADSIZE + EB_UT_LEN(3)) +#define EB_C_UT_SIZE (EB_HEADSIZE + EB_UT_LEN(1)) + + +// Macros for writing machine integers to little-endian format +#define PUTSH(a,f) {char _putsh_c=(char)((a)&0xff); wfunc(param,&_putsh_c,1); _putsh_c=(char)((a)>>8); wfunc(param,&_putsh_c,1);} +#define PUTLG(a,f) {PUTSH((a) & 0xffff,(f)) PUTSH((a) >> 16,(f))} + + +// -- Structure of a ZIP file -- +// Signatures for zip file information headers +#define LOCSIG 0x04034b50L +#define CENSIG 0x02014b50L +#define ENDSIG 0x06054b50L +#define EXTLOCSIG 0x08074b50L + + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +// The minimum and maximum match lengths + + +#define WSIZE (0x8000) +// Maximum window size = 32K. If you are really short of memory, compile +// with a smaller WSIZE but this reduces the compression ratio for files +// of size > WSIZE. WSIZE must be a power of two in the current implementation. +// + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +// Minimum amount of lookahead, except at the end of the input file. +// See deflate.c for comments about the MIN_MATCH+1. +// + +#define MAX_DIST (WSIZE-MIN_LOOKAHEAD) +// In order to simplify the code, particularly on 16 bit machines, match +// distances are limited to MAX_DIST instead of WSIZE. +// + + +#define ZIP_HANDLE 1 +#define ZIP_FILENAME 2 +#define ZIP_MEMORY 3 +#define ZIP_FOLDER 4 + + + +// =========================================================================== +// Constants +// + +#define MAX_BITS 15 +// All codes must not exceed MAX_BITS bits + +#define MAX_BL_BITS 7 +// Bit length codes must not exceed MAX_BL_BITS bits + +#define LENGTH_CODES 29 +// number of length codes, not counting the special END_BLOCK code + +#define LITERALS 256 +// number of literal bytes 0..255 + +#define END_BLOCK 256 +// end of block literal code + +#define L_CODES (LITERALS+1+LENGTH_CODES) +// number of Literal or Length codes, including the END_BLOCK code + +#define D_CODES 30 +// number of distance codes + +#define BL_CODES 19 +// number of codes used to transfer the bit lengths + + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +// The three kinds of block type + +#define LIT_BUFSIZE 0x8000 +#define DIST_BUFSIZE LIT_BUFSIZE +// Sizes of match buffers for literals/lengths and distances. There are +// 4 reasons for limiting LIT_BUFSIZE to 64K: +// - frequencies can be kept in 16 bit counters +// - if compression is not successful for the first block, all input data is +// still in the window so we can still emit a stored block even when input +// comes from standard input. (This can also be done for all blocks if +// LIT_BUFSIZE is not greater than 32K.) +// - if compression is not successful for a file smaller than 64K, we can +// even emit a stored file instead of a stored block (saving 5 bytes). +// - creating new Huffman trees less frequently may not provide fast +// adaptation to changes in the input data statistics. (Take for +// example a binary file with poorly compressible code followed by +// a highly compressible string table.) Smaller buffer sizes give +// fast adaptation but have of course the overhead of transmitting trees +// more frequently. +// - I can't count above 4 +// The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save +// memory at the expense of compression). Some optimizations would be possible +// if we rely on DIST_BUFSIZE == LIT_BUFSIZE. +// + +#define REP_3_6 16 +// repeat previous bit length 3-6 times (2 bits of repeat count) + +#define REPZ_3_10 17 +// repeat a zero length 3-10 times (3 bits of repeat count) + +#define REPZ_11_138 18 +// repeat a zero length 11-138 times (7 bits of repeat count) + +#define HEAP_SIZE (2*L_CODES+1) +// maximum heap size + + +// =========================================================================== +// Local data used by the "bit string" routines. +// + +#define Buf_size (8 * 2*sizeof(char)) +// Number of bits used within bi_buf. (bi_buf may be implemented on +// more than 16 bits on some systems.) + +// Output a 16 bit value to the bit stream, lower (oldest) byte first +#define PUTSHORT(state,w) \ +{ if (state.bs.out_offset >= state.bs.out_size-1) \ + state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); \ + state.bs.out_buf[state.bs.out_offset++] = (char) ((w) & 0xff); \ + state.bs.out_buf[state.bs.out_offset++] = (char) ((ush)(w) >> 8); \ +} + +#define PUTBYTE(state,b) \ +{ if (state.bs.out_offset >= state.bs.out_size) \ + state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); \ + state.bs.out_buf[state.bs.out_offset++] = (char) (b); \ +} + +// DEFLATE.CPP HEADER + +#define HASH_BITS 15 +// For portability to 16 bit machines, do not use values above 15. + +#define HASH_SIZE (unsigned)(1<= HASH_BITS + +#define max_insert_length max_lazy_match +// Insert new strings in the hash table only if the match length +// is not greater than this length. This saves time but degrades compression. +// max_insert_length is used only for compression levels <= 3. + + + +const int extra_lbits[LENGTH_CODES] // extra bits for each length code + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +const int extra_dbits[D_CODES] // extra bits for each distance code + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +const int extra_blbits[BL_CODES]// extra bits for each bit length code + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +const uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +// The lengths of the bit length codes are sent in order of decreasing +// probability, to avoid transmitting the lengths for unused bit length codes. + + +typedef struct config { + ush good_length; // reduce lazy search above this match length + ush max_lazy; // do not perform lazy search above this match length + ush nice_length; // quit search above this match length + ush max_chain; +} config; + +// Values for max_lazy_match, good_match, nice_match and max_chain_length, +// depending on the desired pack level (0..9). The values given below have +// been tuned to exclude worst case performance for pathological files. +// Better values may be found for specific files. +// + +const config configuration_table[10] = { +// good lazy nice chain + {0, 0, 0, 0}, // 0 store only + {4, 4, 8, 4}, // 1 maximum speed, no lazy matches + {4, 5, 16, 8}, // 2 + {4, 6, 32, 32}, // 3 + {4, 4, 16, 16}, // 4 lazy matches */ + {8, 16, 32, 32}, // 5 + {8, 16, 128, 128}, // 6 + {8, 32, 128, 256}, // 7 + {32, 128, 258, 1024}, // 8 + {32, 258, 258, 4096}};// 9 maximum compression */ + +// Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 +// For deflate_fast() (levels <= 3) good is ignored and lazy has a different meaning. + + + + + + + +// Data structure describing a single value and its code string. +typedef struct ct_data { + union { + ush freq; // frequency count + ush code; // bit string + } fc; + union { + ush dad; // father node in Huffman tree + ush len; // length of bit string + } dl; +} ct_data; + +typedef struct tree_desc { + ct_data *dyn_tree; // the dynamic tree + ct_data *static_tree; // corresponding static tree or NULL + const int *extra_bits; // extra bits for each code or NULL + int extra_base; // base index for extra_bits + int elems; // max number of elements in the tree + int max_length; // max bit length for the codes + int max_code; // largest code with non zero frequency +} tree_desc; + + + + +class TTreeState +{ public: + TTreeState(); + + ct_data dyn_ltree[HEAP_SIZE]; // literal and length tree + ct_data dyn_dtree[2*D_CODES+1]; // distance tree + ct_data static_ltree[L_CODES+2]; // the static literal tree... + // ... Since the bit lengths are imposed, there is no need for the L_CODES + // extra codes used during heap construction. However the codes 286 and 287 + // are needed to build a canonical tree (see ct_init below). + ct_data static_dtree[D_CODES]; // the static distance tree... + // ... (Actually a trivial tree since all codes use 5 bits.) + ct_data bl_tree[2*BL_CODES+1]; // Huffman tree for the bit lengths + + tree_desc l_desc; + tree_desc d_desc; + tree_desc bl_desc; + + ush bl_count[MAX_BITS+1]; // number of codes at each bit length for an optimal tree + + int heap[2*L_CODES+1]; // heap used to build the Huffman trees + int heap_len; // number of elements in the heap + int heap_max; // element of largest frequency + // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + // The same heap array is used to build all trees. + + uch depth[2*L_CODES+1]; + // Depth of each subtree used as tie breaker for trees of equal frequency + + uch length_code[MAX_MATCH-MIN_MATCH+1]; + // length code for each normalized match length (0 == MIN_MATCH) + + uch dist_code[512]; + // distance codes. The first 256 values correspond to the distances + // 3 .. 258, the last 256 values correspond to the top 8 bits of + // the 15 bit distances. + + int base_length[LENGTH_CODES]; + // First normalized length for each code (0 = MIN_MATCH) + + int base_dist[D_CODES]; + // First normalized distance for each code (0 = distance of 1) + + uch far l_buf[LIT_BUFSIZE]; // buffer for literals/lengths + ush far d_buf[DIST_BUFSIZE]; // buffer for distances + + uch flag_buf[(LIT_BUFSIZE/8)]; + // flag_buf is a bit array distinguishing literals from lengths in + // l_buf, and thus indicating the presence or absence of a distance. + + unsigned last_lit; // running index in l_buf + unsigned last_dist; // running index in d_buf + unsigned last_flags; // running index in flag_buf + uch flags; // current flags not yet saved in flag_buf + uch flag_bit; // current bit used in flags + // bits are filled in flags starting at bit 0 (least significant). + // Note: these flags are overkill in the current code since we don't + // take advantage of DIST_BUFSIZE == LIT_BUFSIZE. + + ulg opt_len; // bit length of current block with optimal trees + ulg static_len; // bit length of current block with static trees + + ulg cmpr_bytelen; // total byte length of compressed file + ulg cmpr_len_bits; // number of bits past 'cmpr_bytelen' + + ulg input_len; // total byte length of input file + // input_len is for debugging only since we can get it by other means. + + ush *file_type; // pointer to UNKNOWN, BINARY or ASCII +// int *file_method; // pointer to DEFLATE or STORE +}; + +TTreeState::TTreeState() +{ tree_desc a = {dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0}; l_desc = a; + tree_desc b = {dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0}; d_desc = b; + tree_desc c = {bl_tree, NULL, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0}; bl_desc = c; + last_lit=0; + last_dist=0; + last_flags=0; +} + + + +class TBitState +{ public: + + int flush_flg; + // + unsigned bi_buf; + // Output buffer. bits are inserted starting at the bottom (least significant + // bits). The width of bi_buf must be at least 16 bits. + int bi_valid; + // Number of valid bits in bi_buf. All bits above the last valid bit + // are always zero. + char *out_buf; + // Current output buffer. + unsigned out_offset; + // Current offset in output buffer. + // On 16 bit machines, the buffer is limited to 64K. + unsigned out_size; + // Size of current output buffer + ulg bits_sent; // bit length of the compressed data only needed for debugging??? +}; + + + + + + + +class TDeflateState +{ public: + TDeflateState() {window_size=0;} + + uch window[2L*WSIZE]; + // Sliding window. Input bytes are read into the second half of the window, + // and move to the first half later to keep a dictionary of at least WSIZE + // bytes. With this organization, matches are limited to a distance of + // WSIZE-MAX_MATCH bytes, but this ensures that IO is always + // performed with a length multiple of the block size. Also, it limits + // the window size to 64K, which is quite useful on MSDOS. + // To do: limit the window size to WSIZE+CBSZ if SMALL_MEM (the code would + // be less efficient since the data would have to be copied WSIZE/CBSZ times) + Pos prev[WSIZE]; + // Link to older string with same hash index. To limit the size of this + // array to 64K, this link is maintained only for the last 32K strings. + // An index in this array is thus a window index modulo 32K. + Pos head[HASH_SIZE]; + // Heads of the hash chains or NIL. If your compiler thinks that + // HASH_SIZE is a dynamic value, recompile with -DDYN_ALLOC. + + ulg window_size; + // window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the + // input file length plus MIN_LOOKAHEAD. + + long block_start; + // window position at the beginning of the current output block. Gets + // negative when the window is moved backwards. + + int sliding; + // Set to false when the input file is already in memory + + unsigned ins_h; // hash index of string to be inserted + + unsigned int prev_length; + // Length of the best match at previous step. Matches not greater than this + // are discarded. This is used in the lazy match evaluation. + + unsigned strstart; // start of string to insert + unsigned match_start; // start of matching string + int eofile; // flag set at end of input file + unsigned lookahead; // number of valid bytes ahead in window + + unsigned max_chain_length; + // To speed up deflation, hash chains are never searched beyond this length. + // A higher limit improves compression ratio but degrades the speed. + + unsigned int max_lazy_match; + // Attempt to find a better match only when the current match is strictly + // smaller than this value. This mechanism is used only for compression + // levels >= 4. + + unsigned good_match; + // Use a faster search when the previous match is longer than this + + int nice_match; // Stop searching when current match exceeds this +}; + +typedef __int64 lutime_t; // define it ourselves since we don't include time.h + +typedef struct iztimes { + lutime_t atime,mtime,ctime; +} iztimes; // access, modify, create times + +typedef struct zlist { + ush vem, ver, flg, how; // See central header in zipfile.c for what vem..off are + ulg tim, crc, siz, len; + extent nam, ext, cext, com; // offset of ext must be >= LOCHEAD + ush dsk, att, lflg; // offset of lflg must be >= LOCHEAD + ulg atx, off; + char name[MAX_PATH]; // File name in zip file + char *extra; // Extra field (set only if ext != 0) + char *cextra; // Extra in central (set only if cext != 0) + char *comment; // Comment (set only if com != 0) + char iname[MAX_PATH]; // Internal file name after cleanup + char zname[MAX_PATH]; // External version of internal name + int mark; // Marker for files to operate on + int trash; // Marker for files to delete + int dosflag; // Set to force MSDOS file attributes + struct zlist far *nxt; // Pointer to next header in list +} TZipFileInfo; + + +struct TState; +typedef unsigned (*READFUNC)(TState &state, char *buf,unsigned size); +typedef unsigned (*FLUSHFUNC)(void *param, const char *buf, unsigned *size); +typedef unsigned (*WRITEFUNC)(void *param, const char *buf, unsigned size); +struct TState +{ void *param; + int level; bool seekable; + READFUNC readfunc; FLUSHFUNC flush_outbuf; + TTreeState ts; TBitState bs; TDeflateState ds; + const char *err; +}; + + + + + + + + + +void Assert(TState &state,bool cond, const char *msg) +{ if (cond) return; + state.err=msg; +} +void __cdecl Trace(const char *x, ...) {va_list paramList; va_start(paramList, x); paramList; va_end(paramList);} +void __cdecl Tracec(bool ,const char *x, ...) {va_list paramList; va_start(paramList, x); paramList; va_end(paramList);} + + + +// =========================================================================== +// Local (static) routines in this file. +// + +void init_block (TState &); +void pqdownheap (TState &,ct_data *tree, int k); +void gen_bitlen (TState &,tree_desc *desc); +void gen_codes (TState &state,ct_data *tree, int max_code); +void build_tree (TState &,tree_desc *desc); +void scan_tree (TState &,ct_data *tree, int max_code); +void send_tree (TState &state,ct_data *tree, int max_code); +int build_bl_tree (TState &); +void send_all_trees (TState &state,int lcodes, int dcodes, int blcodes); +void compress_block (TState &state,ct_data *ltree, ct_data *dtree); +void set_file_type (TState &); +void send_bits (TState &state, int value, int length); +unsigned bi_reverse (unsigned code, int len); +void bi_windup (TState &state); +void copy_block (TState &state,char *buf, unsigned len, int header); + + +#define send_code(state, c, tree) send_bits(state, tree[c].fc.code, tree[c].dl.len) +// Send a code of the given tree. c and tree must not have side effects + +// alternatively... +//#define send_code(state, c, tree) +// { if (state.verbose>1) fprintf(stderr,"\ncd %3d ",(c)); +// send_bits(state, tree[c].fc.code, tree[c].dl.len); } + +#define d_code(dist) ((dist) < 256 ? state.ts.dist_code[dist] : state.ts.dist_code[256+((dist)>>7)]) +// Mapping from a distance to a distance code. dist is the distance - 1 and +// must not have side effects. dist_code[256] and dist_code[257] are never used. + +#define Max(a,b) (a >= b ? a : b) +/* the arguments must not have side effects */ + +/* =========================================================================== + * Allocate the match buffer, initialize the various tables and save the + * location of the internal file attribute (ascii/binary) and method + * (DEFLATE/STORE). + */ +void ct_init(TState &state, ush *attr) +{ + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + + state.ts.file_type = attr; + //state.ts.file_method = method; + state.ts.cmpr_bytelen = state.ts.cmpr_len_bits = 0L; + state.ts.input_len = 0L; + + if (state.ts.static_dtree[0].dl.len != 0) return; /* ct_init already called */ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + state.ts.base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + state.ts.base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + state.ts.base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + state.ts.dist_code[256 + dist++] = (uch)code; + } + } + Assert(state,dist == 256, "ct_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) state.ts.bl_count[bits] = 0; + n = 0; + while (n <= 143) state.ts.static_ltree[n++].dl.len = 8, state.ts.bl_count[8]++; + while (n <= 255) state.ts.static_ltree[n++].dl.len = 9, state.ts.bl_count[9]++; + while (n <= 279) state.ts.static_ltree[n++].dl.len = 7, state.ts.bl_count[7]++; + while (n <= 287) state.ts.static_ltree[n++].dl.len = 8, state.ts.bl_count[8]++; + /* fc.codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(state,(ct_data *)state.ts.static_ltree, L_CODES+1); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + state.ts.static_dtree[n].dl.len = 5; + state.ts.static_dtree[n].fc.code = (ush)bi_reverse(n, 5); + } + + /* Initialize the first block of the first file: */ + init_block(state); +} + +/* =========================================================================== + * Initialize a new block. + */ +void init_block(TState &state) +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) state.ts.dyn_ltree[n].fc.freq = 0; + for (n = 0; n < D_CODES; n++) state.ts.dyn_dtree[n].fc.freq = 0; + for (n = 0; n < BL_CODES; n++) state.ts.bl_tree[n].fc.freq = 0; + + state.ts.dyn_ltree[END_BLOCK].fc.freq = 1; + state.ts.opt_len = state.ts.static_len = 0L; + state.ts.last_lit = state.ts.last_dist = state.ts.last_flags = 0; + state.ts.flags = 0; state.ts.flag_bit = 1; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(tree, top) \ +{\ + top = state.ts.heap[SMALLEST]; \ + state.ts.heap[SMALLEST] = state.ts.heap[state.ts.heap_len--]; \ + pqdownheap(state,tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m) \ + (tree[n].fc.freq < tree[m].fc.freq || \ + (tree[n].fc.freq == tree[m].fc.freq && state.ts.depth[n] <= state.ts.depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +void pqdownheap(TState &state,ct_data *tree, int k) +{ + int v = state.ts.heap[k]; + int j = k << 1; /* left son of k */ + int htemp; /* required because of bug in SASC compiler */ + + while (j <= state.ts.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < state.ts.heap_len && smaller(tree, state.ts.heap[j+1], state.ts.heap[j])) j++; + + /* Exit if v is smaller than both sons */ + htemp = state.ts.heap[j]; + if (smaller(tree, v, htemp)) break; + + /* Exchange v with the smallest son */ + state.ts.heap[k] = htemp; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + state.ts.heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +void gen_bitlen(TState &state,tree_desc *desc) +{ + ct_data *tree = desc->dyn_tree; + const int *extra = desc->extra_bits; + int base = desc->extra_base; + int max_code = desc->max_code; + int max_length = desc->max_length; + ct_data *stree = desc->static_tree; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) state.ts.bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[state.ts.heap[state.ts.heap_max]].dl.len = 0; /* root of the heap */ + + for (h = state.ts.heap_max+1; h < HEAP_SIZE; h++) { + n = state.ts.heap[h]; + bits = tree[tree[n].dl.dad].dl.len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].dl.len = (ush)bits; + /* We overwrite tree[n].dl.dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + state.ts.bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].fc.freq; + state.ts.opt_len += (ulg)f * (bits + xbits); + if (stree) state.ts.static_len += (ulg)f * (stree[n].dl.len + xbits); + } + if (overflow == 0) return; + + Trace("\nbit length overflow\n"); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (state.ts.bl_count[bits] == 0) bits--; + state.ts.bl_count[bits]--; /* move one leaf down the tree */ + state.ts.bl_count[bits+1] += (ush)2; /* move one overflow item as its brother */ + state.ts.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = state.ts.bl_count[bits]; + while (n != 0) { + m = state.ts.heap[--h]; + if (m > max_code) continue; + if (tree[m].dl.len != (ush)bits) { + Trace("code %d bits %d->%d\n", m, tree[m].dl.len, bits); + state.ts.opt_len += ((long)bits-(long)tree[m].dl.len)*(long)tree[m].fc.freq; + tree[m].dl.len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +void gen_codes (TState &state, ct_data *tree, int max_code) +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (ush)((code + state.ts.bl_count[bits-1]) << 1); + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert(state,code + state.ts.bl_count[MAX_BITS]-1 == (1<< ((ush) MAX_BITS)) - 1, + "inconsistent bit counts"); + Trace("\ngen_codes: max_code %d ", max_code); + + for (n = 0; n <= max_code; n++) { + int len = tree[n].dl.len; + if (len == 0) continue; + /* Now reverse the bits */ + tree[n].fc.code = (ush)bi_reverse(next_code[len]++, len); + + //Tracec(tree != state.ts.static_ltree, "\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].fc.code, next_code[len]-1); + } +} + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +void build_tree(TState &state,tree_desc *desc) +{ + ct_data *tree = desc->dyn_tree; + ct_data *stree = desc->static_tree; + int elems = desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node = elems; /* next internal node of the tree */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + state.ts.heap_len = 0, state.ts.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].fc.freq != 0) { + state.ts.heap[++state.ts.heap_len] = max_code = n; + state.ts.depth[n] = 0; + } else { + tree[n].dl.len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (state.ts.heap_len < 2) { + int newcp = state.ts.heap[++state.ts.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[newcp].fc.freq = 1; + state.ts.depth[newcp] = 0; + state.ts.opt_len--; if (stree) state.ts.static_len -= stree[newcp].dl.len; + /* new is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = state.ts.heap_len/2; n >= 1; n--) pqdownheap(state,tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + do { + pqremove(tree, n); /* n = node of least frequency */ + m = state.ts.heap[SMALLEST]; /* m = node of next least frequency */ + + state.ts.heap[--state.ts.heap_max] = n; /* keep the nodes sorted by frequency */ + state.ts.heap[--state.ts.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node].fc.freq = (ush)(tree[n].fc.freq + tree[m].fc.freq); + state.ts.depth[node] = (uch) (Max(state.ts.depth[n], state.ts.depth[m]) + 1); + tree[n].dl.dad = tree[m].dl.dad = (ush)node; + /* and insert the new node in the heap */ + state.ts.heap[SMALLEST] = node++; + pqdownheap(state,tree, SMALLEST); + + } while (state.ts.heap_len >= 2); + + state.ts.heap[--state.ts.heap_max] = state.ts.heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(state,(tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes (state,(ct_data *)tree, max_code); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. Updates opt_len to take into account the repeat + * counts. (The contribution of the bit length codes will be added later + * during the construction of bl_tree.) + */ +void scan_tree (TState &state,ct_data *tree, int max_code) +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].dl.len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].dl.len = (ush)-1; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].dl.len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + state.ts.bl_tree[curlen].fc.freq = (ush)(state.ts.bl_tree[curlen].fc.freq + count); + } else if (curlen != 0) { + if (curlen != prevlen) state.ts.bl_tree[curlen].fc.freq++; + state.ts.bl_tree[REP_3_6].fc.freq++; + } else if (count <= 10) { + state.ts.bl_tree[REPZ_3_10].fc.freq++; + } else { + state.ts.bl_tree[REPZ_11_138].fc.freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +void send_tree (TState &state, ct_data *tree, int max_code) +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].dl.len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].dl.len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].dl.len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(state, curlen, state.ts.bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(state, curlen, state.ts.bl_tree); count--; + } + Assert(state,count >= 3 && count <= 6, " 3_6?"); + send_code(state,REP_3_6, state.ts.bl_tree); send_bits(state,count-3, 2); + + } else if (count <= 10) { + send_code(state,REPZ_3_10, state.ts.bl_tree); send_bits(state,count-3, 3); + + } else { + send_code(state,REPZ_11_138, state.ts.bl_tree); send_bits(state,count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +int build_bl_tree(TState &state) +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(state,(ct_data *)state.ts.dyn_ltree, state.ts.l_desc.max_code); + scan_tree(state,(ct_data *)state.ts.dyn_dtree, state.ts.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(state,(tree_desc *)(&state.ts.bl_desc)); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (state.ts.bl_tree[bl_order[max_blindex]].dl.len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + state.ts.opt_len += 3*(max_blindex+1) + 5+5+4; + Trace("\ndyn trees: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +void send_all_trees(TState &state,int lcodes, int dcodes, int blcodes) +{ + int rank; /* index in bl_order */ + + Assert(state,lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert(state,lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Trace("\nbl counts: "); + send_bits(state,lcodes-257, 5); + /* not +255 as stated in appnote.txt 1.93a or -256 in 2.04c */ + send_bits(state,dcodes-1, 5); + send_bits(state,blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Trace("\nbl code %2d ", bl_order[rank]); + send_bits(state,state.ts.bl_tree[bl_order[rank]].dl.len, 3); + } + Trace("\nbl tree: sent %ld", state.bs.bits_sent); + + send_tree(state,(ct_data *)state.ts.dyn_ltree, lcodes-1); /* send the literal tree */ + Trace("\nlit tree: sent %ld", state.bs.bits_sent); + + send_tree(state,(ct_data *)state.ts.dyn_dtree, dcodes-1); /* send the distance tree */ + Trace("\ndist tree: sent %ld", state.bs.bits_sent); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. This function + * returns the total compressed length (in bytes) for the file so far. + */ +ulg flush_block(TState &state,char *buf, ulg stored_len, int eof) +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex; /* index of last bit length code of non zero freq */ + + state.ts.flag_buf[state.ts.last_flags] = state.ts.flags; /* Save the flags for the last 8 items */ + + /* Check if the file is ascii or binary */ + if (*state.ts.file_type == (ush)UNKNOWN) set_file_type(state); + + /* Construct the literal and distance trees */ + build_tree(state,(tree_desc *)(&state.ts.l_desc)); + Trace("\nlit data: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len); + + build_tree(state,(tree_desc *)(&state.ts.d_desc)); + Trace("\ndist data: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(state); + + /* Determine the best encoding. Compute first the block length in bytes */ + opt_lenb = (state.ts.opt_len+3+7)>>3; + static_lenb = (state.ts.static_len+3+7)>>3; + state.ts.input_len += stored_len; /* for debugging only */ + + Trace("\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ", + opt_lenb, state.ts.opt_len, static_lenb, state.ts.static_len, stored_len, + state.ts.last_lit, state.ts.last_dist); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + // Originally, zip allowed the file to be transformed from a compressed + // into a stored file in the case where compression failed, there + // was only one block, and it was allowed to change. I've removed this + // possibility since the code's cleaner if no changes are allowed. + //if (stored_len <= opt_lenb && eof && state.ts.cmpr_bytelen == 0L + // && state.ts.cmpr_len_bits == 0L && state.seekable) + //{ // && state.ts.file_method != NULL + // // Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: + // Assert(state,buf!=NULL,"block vanished"); + // copy_block(state,buf, (unsigned)stored_len, 0); // without header + // state.ts.cmpr_bytelen = stored_len; + // Assert(state,false,"unimplemented *state.ts.file_method = STORE;"); + // //*state.ts.file_method = STORE; + //} + //else + if (stored_len+4 <= opt_lenb && buf != (char*)NULL) { + /* 4: two words for the lengths */ + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + send_bits(state,(STORED_BLOCK<<1)+eof, 3); /* send block type */ + state.ts.cmpr_bytelen += ((state.ts.cmpr_len_bits + 3 + 7) >> 3) + stored_len + 4; + state.ts.cmpr_len_bits = 0L; + + copy_block(state,buf, (unsigned)stored_len, 1); /* with header */ + } + else if (static_lenb == opt_lenb) { + send_bits(state,(STATIC_TREES<<1)+eof, 3); + compress_block(state,(ct_data *)state.ts.static_ltree, (ct_data *)state.ts.static_dtree); + state.ts.cmpr_len_bits += 3 + state.ts.static_len; + state.ts.cmpr_bytelen += state.ts.cmpr_len_bits >> 3; + state.ts.cmpr_len_bits &= 7L; + } + else { + send_bits(state,(DYN_TREES<<1)+eof, 3); + send_all_trees(state,state.ts.l_desc.max_code+1, state.ts.d_desc.max_code+1, max_blindex+1); + compress_block(state,(ct_data *)state.ts.dyn_ltree, (ct_data *)state.ts.dyn_dtree); + state.ts.cmpr_len_bits += 3 + state.ts.opt_len; + state.ts.cmpr_bytelen += state.ts.cmpr_len_bits >> 3; + state.ts.cmpr_len_bits &= 7L; + } + Assert(state,((state.ts.cmpr_bytelen << 3) + state.ts.cmpr_len_bits) == state.bs.bits_sent, "bad compressed size"); + init_block(state); + + if (eof) { + // Assert(state,input_len == isize, "bad input size"); + bi_windup(state); + state.ts.cmpr_len_bits += 7; /* align on byte boundary */ + } + Trace("\n"); + + return state.ts.cmpr_bytelen + (state.ts.cmpr_len_bits >> 3); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ct_tally (TState &state,int dist, int lc) +{ + state.ts.l_buf[state.ts.last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + state.ts.dyn_ltree[lc].fc.freq++; + } else { + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert(state,(ush)dist < (ush)MAX_DIST && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match"); + + state.ts.dyn_ltree[state.ts.length_code[lc]+LITERALS+1].fc.freq++; + state.ts.dyn_dtree[d_code(dist)].fc.freq++; + + state.ts.d_buf[state.ts.last_dist++] = (ush)dist; + state.ts.flags |= state.ts.flag_bit; + } + state.ts.flag_bit <<= 1; + + /* Output the flags if they fill a byte: */ + if ((state.ts.last_lit & 7) == 0) { + state.ts.flag_buf[state.ts.last_flags++] = state.ts.flags; + state.ts.flags = 0, state.ts.flag_bit = 1; + } + /* Try to guess if it is profitable to stop the current block here */ + if (state.level > 2 && (state.ts.last_lit & 0xfff) == 0) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)state.ts.last_lit*8L; + ulg in_length = (ulg)state.ds.strstart-state.ds.block_start; + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)state.ts.dyn_dtree[dcode].fc.freq*(5L+extra_dbits[dcode]); + } + out_length >>= 3; + Trace("\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ", + state.ts.last_lit, state.ts.last_dist, in_length, out_length, + 100L - out_length*100L/in_length); + if (state.ts.last_dist < state.ts.last_lit/2 && out_length < in_length/2) return 1; + } + return (state.ts.last_lit == LIT_BUFSIZE-1 || state.ts.last_dist == DIST_BUFSIZE); + /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +void compress_block(TState &state,ct_data *ltree, ct_data *dtree) +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned dx = 0; /* running index in d_buf */ + unsigned fx = 0; /* running index in flag_buf */ + uch flag = 0; /* current flags */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (state.ts.last_lit != 0) do { + if ((lx & 7) == 0) flag = state.ts.flag_buf[fx++]; + lc = state.ts.l_buf[lx++]; + if ((flag & 1) == 0) { + send_code(state,lc, ltree); /* send a literal byte */ + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = state.ts.length_code[lc]; + send_code(state,code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= state.ts.base_length[code]; + send_bits(state,lc, extra); /* send the extra length bits */ + } + dist = state.ts.d_buf[dx++]; + /* Here, dist is the match distance - 1 */ + code = d_code(dist); + Assert(state,code < D_CODES, "bad d_code"); + + send_code(state,code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= state.ts.base_dist[code]; + send_bits(state,dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + flag >>= 1; + } while (lx < state.ts.last_lit); + + send_code(state,END_BLOCK, ltree); +} + +/* =========================================================================== + * Set the file type to ASCII or BINARY, using a crude approximation: + * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. + * IN assertion: the fields freq of dyn_ltree are set and the total of all + * frequencies does not exceed 64K (to fit in an int on 16 bit machines). + */ +void set_file_type(TState &state) +{ + int n = 0; + unsigned ascii_freq = 0; + unsigned bin_freq = 0; + while (n < 7) bin_freq += state.ts.dyn_ltree[n++].fc.freq; + while (n < 128) ascii_freq += state.ts.dyn_ltree[n++].fc.freq; + while (n < LITERALS) bin_freq += state.ts.dyn_ltree[n++].fc.freq; + *state.ts.file_type = (ush)(bin_freq > (ascii_freq >> 2) ? BINARY : ASCII); +} + + +/* =========================================================================== + * Initialize the bit string routines. + */ +void bi_init (TState &state,char *tgt_buf, unsigned tgt_size, int flsh_allowed) +{ + state.bs.out_buf = tgt_buf; + state.bs.out_size = tgt_size; + state.bs.out_offset = 0; + state.bs.flush_flg = flsh_allowed; + + state.bs.bi_buf = 0; + state.bs.bi_valid = 0; + state.bs.bits_sent = 0L; +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +void send_bits(TState &state,int value, int length) +{ + Assert(state,length > 0 && length <= 15, "invalid length"); + state.bs.bits_sent += (ulg)length; + /* If not enough room in bi_buf, use (bi_valid) bits from bi_buf and + * (Buf_size - bi_valid) bits from value to flush the filled bi_buf, + * then fill in the rest of (value), leaving (length - (Buf_size-bi_valid)) + * unused bits in bi_buf. + */ + state.bs.bi_buf |= (value << state.bs.bi_valid); + state.bs.bi_valid += length; + if (state.bs.bi_valid > (int)Buf_size) { + PUTSHORT(state,state.bs.bi_buf); + state.bs.bi_valid -= Buf_size; + state.bs.bi_buf = (unsigned)value >> (length - state.bs.bi_valid); + } +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +unsigned bi_reverse(unsigned code, int len) +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Write out any remaining bits in an incomplete byte. + */ +void bi_windup(TState &state) +{ + if (state.bs.bi_valid > 8) { + PUTSHORT(state,state.bs.bi_buf); + } else if (state.bs.bi_valid > 0) { + PUTBYTE(state,state.bs.bi_buf); + } + if (state.bs.flush_flg) { + state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); + } + state.bs.bi_buf = 0; + state.bs.bi_valid = 0; + state.bs.bits_sent = (state.bs.bits_sent+7) & ~7; +} + +/* =========================================================================== + * Copy a stored block to the zip file, storing first the length and its + * one's complement if requested. + */ +void copy_block(TState &state, char *block, unsigned len, int header) +{ + bi_windup(state); /* align on byte boundary */ + + if (header) { + PUTSHORT(state,(ush)len); + PUTSHORT(state,(ush)~len); + state.bs.bits_sent += 2*16; + } + if (state.bs.flush_flg) { + state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); + state.bs.out_offset = len; + state.flush_outbuf(state.param,block, &state.bs.out_offset); + } else if (state.bs.out_offset + len > state.bs.out_size) { + Assert(state,false,"output buffer too small for in-memory compression"); + } else { + memcpy(state.bs.out_buf + state.bs.out_offset, block, len); + state.bs.out_offset += len; + } + state.bs.bits_sent += (ulg)len<<3; +} + + + + + + + + +/* =========================================================================== + * Prototypes for functions. + */ + +void fill_window (TState &state); +ulg deflate_fast (TState &state); + +int longest_match (TState &state,IPos cur_match); + + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(h,c) (h = (((h)< 0 if the input file is already read or + * mmap'ed in the window[] array, 0 otherwise. In the first case, + * window_size is sufficient to contain the whole input file plus + * MIN_LOOKAHEAD bytes (to avoid referencing memory beyond the end + * of window[] when looking for matches towards the end). + */ +void lm_init (TState &state, int pack_level, ush *flags) +{ + register unsigned j; + + Assert(state,pack_level>=1 && pack_level<=8,"bad pack level"); + + /* Do not slide the window if the whole input is already in memory + * (window_size > 0) + */ + state.ds.sliding = 0; + if (state.ds.window_size == 0L) { + state.ds.sliding = 1; + state.ds.window_size = (ulg)2L*WSIZE; + } + + /* Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ + state.ds.head[HASH_SIZE-1] = NIL; + memset((char*)state.ds.head, NIL, (unsigned)(HASH_SIZE-1)*sizeof(*state.ds.head)); + + /* Set the default configuration parameters: + */ + state.ds.max_lazy_match = configuration_table[pack_level].max_lazy; + state.ds.good_match = configuration_table[pack_level].good_length; + state.ds.nice_match = configuration_table[pack_level].nice_length; + state.ds.max_chain_length = configuration_table[pack_level].max_chain; + if (pack_level <= 2) { + *flags |= FAST; + } else if (pack_level >= 8) { + *flags |= SLOW; + } + /* ??? reduce max_chain_length for binary files */ + + state.ds.strstart = 0; + state.ds.block_start = 0L; + + j = WSIZE; + j <<= 1; // Can read 64K in one step + state.ds.lookahead = state.readfunc(state, (char*)state.ds.window, j); + + if (state.ds.lookahead == 0 || state.ds.lookahead == (unsigned)EOF) { + state.ds.eofile = 1, state.ds.lookahead = 0; + return; + } + state.ds.eofile = 0; + /* Make sure that we always have enough lookahead. This is important + * if input comes from a device such as a tty. + */ + if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state); + + state.ds.ins_h = 0; + for (j=0; j= 1 + */ +// For 80x86 and 680x0 and ARM, an optimized version is in match.asm or +// match.S. The code is functionally equivalent, so you can use the C version +// if desired. Which I do so desire! +int longest_match(TState &state,IPos cur_match) +{ + unsigned chain_length = state.ds.max_chain_length; /* max hash chain length */ + register uch far *scan = state.ds.window + state.ds.strstart; /* current string */ + register uch far *match; /* matched string */ + register int len; /* length of current match */ + int best_len = state.ds.prev_length; /* best match length so far */ + IPos limit = state.ds.strstart > (IPos)MAX_DIST ? state.ds.strstart - (IPos)MAX_DIST : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + // It is easy to get rid of this optimization if necessary. + Assert(state,HASH_BITS>=8 && MAX_MATCH==258,"Code too clever"); + + + + register uch far *strend = state.ds.window + state.ds.strstart + MAX_MATCH; + register uch scan_end1 = scan[best_len-1]; + register uch scan_end = scan[best_len]; + + /* Do not waste too much time if we already have a good match: */ + if (state.ds.prev_length >= state.ds.good_match) { + chain_length >>= 2; + } + + Assert(state,state.ds.strstart <= state.ds.window_size-MIN_LOOKAHEAD, "insufficient lookahead"); + + do { + Assert(state,cur_match < state.ds.strstart, "no future"); + match = state.ds.window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2: + */ + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(state,scan <= state.ds.window+(unsigned)(state.ds.window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + + + if (len > best_len) { + state.ds.match_start = cur_match; + best_len = len; + if (len >= state.ds.nice_match) break; + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; + } + } while ((cur_match = state.ds.prev[cur_match & WMASK]) > limit + && --chain_length != 0); + + return best_len; +} + + + +#define check_match(state,start, match, length) +// or alternatively... +//void check_match(TState &state,IPos start, IPos match, int length) +//{ // check that the match is indeed a match +// if (memcmp((char*)state.ds.window + match, +// (char*)state.ds.window + start, length) != EQUAL) { +// fprintf(stderr, +// " start %d, match %d, length %d\n", +// start, match, length); +// error("invalid match"); +// } +// if (state.verbose > 1) { +// fprintf(stderr,"\\[%d,%d]", start-match, length); +// do { fprintf(stdout,"%c",state.ds.window[start++]); } while (--length != 0); +// } +//} + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead, and sets eofile if end of input file. + * + * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0 + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or eofile is set; file reads are + * performed for at least two bytes (required for the translate_eol option). + */ +void fill_window(TState &state) +{ + register unsigned n, m; + unsigned more; /* Amount of free space at the end of the window. */ + + do { + more = (unsigned)(state.ds.window_size - (ulg)state.ds.lookahead - (ulg)state.ds.strstart); + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (more == (unsigned)EOF) { + /* Very unlikely, but possible on 16 bit machine if strstart == 0 + * and lookahead == 1 (input done one byte at time) + */ + more--; + + /* For MMAP or BIG_MEM, the whole input file is already in memory so + * we must not perform sliding. We must however call (*read_buf)() in + * order to compute the crc, update lookahead and possibly set eofile. + */ + } else if (state.ds.strstart >= WSIZE+MAX_DIST && state.ds.sliding) { + + /* By the IN assertion, the window is not empty so we can't confuse + * more == 0 with more == 64K on a 16 bit machine. + */ + memcpy((char*)state.ds.window, (char*)state.ds.window+WSIZE, (unsigned)WSIZE); + state.ds.match_start -= WSIZE; + state.ds.strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */ + + state.ds.block_start -= (long) WSIZE; + + for (n = 0; n < HASH_SIZE; n++) { + m = state.ds.head[n]; + state.ds.head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL); + } + for (n = 0; n < WSIZE; n++) { + m = state.ds.prev[n]; + state.ds.prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } + more += WSIZE; + } + if (state.ds.eofile) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the MMAP or BIG_MEM case (not yet supported in gzip), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(state,more >= 2, "more < 2"); + + n = state.readfunc(state, (char*)state.ds.window+state.ds.strstart+state.ds.lookahead, more); + + if (n == 0 || n == (unsigned)EOF) { + state.ds.eofile = 1; + } else { + state.ds.lookahead += n; + } + } while (state.ds.lookahead < MIN_LOOKAHEAD && !state.ds.eofile); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK(state,eof) \ + flush_block(state,state.ds.block_start >= 0L ? (char*)&state.ds.window[(unsigned)state.ds.block_start] : \ + (char*)NULL, (long)state.ds.strstart - state.ds.block_start, (eof)) + +/* =========================================================================== + * Processes a new input file and return its compressed length. This + * function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +ulg deflate_fast(TState &state) +{ + IPos hash_head = NIL; /* head of the hash chain */ + int flush; /* set if current block must be flushed */ + unsigned match_length = 0; /* length of best match */ + + state.ds.prev_length = MIN_MATCH-1; + while (state.ds.lookahead != 0) { + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (state.ds.lookahead >= MIN_MATCH) + INSERT_STRING(state.ds.strstart, hash_head); + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && state.ds.strstart - hash_head <= MAX_DIST) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + /* Do not look for matches beyond the end of the input. + * This is necessary to make deflate deterministic. + */ + if ((unsigned)state.ds.nice_match > state.ds.lookahead) state.ds.nice_match = (int)state.ds.lookahead; + match_length = longest_match (state,hash_head); + /* longest_match() sets match_start */ + if (match_length > state.ds.lookahead) match_length = state.ds.lookahead; + } + if (match_length >= MIN_MATCH) { + check_match(state,state.ds.strstart, state.ds.match_start, match_length); + + flush = ct_tally(state,state.ds.strstart-state.ds.match_start, match_length - MIN_MATCH); + + state.ds.lookahead -= match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (match_length <= state.ds.max_insert_length + && state.ds.lookahead >= MIN_MATCH) { + match_length--; /* string at strstart already in hash table */ + do { + state.ds.strstart++; + INSERT_STRING(state.ds.strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--match_length != 0); + state.ds.strstart++; + } else { + state.ds.strstart += match_length; + match_length = 0; + state.ds.ins_h = state.ds.window[state.ds.strstart]; + UPDATE_HASH(state.ds.ins_h, state.ds.window[state.ds.strstart+1]); + Assert(state,MIN_MATCH==3,"Call UPDATE_HASH() MIN_MATCH-3 more times"); + } + } else { + /* No match, output a literal byte */ + flush = ct_tally (state,0, state.ds.window[state.ds.strstart]); + state.ds.lookahead--; + state.ds.strstart++; + } + if (flush) FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart; + + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state); + } + return FLUSH_BLOCK(state,1); /* eof */ +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +ulg deflate(TState &state) +{ + IPos hash_head = NIL; /* head of hash chain */ + IPos prev_match; /* previous match */ + int flush; /* set if current block must be flushed */ + int match_available = 0; /* set if previous match exists */ + register unsigned match_length = MIN_MATCH-1; /* length of best match */ + + if (state.level <= 3) return deflate_fast(state); /* optimized for speed */ + + /* Process the input block. */ + while (state.ds.lookahead != 0) { + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (state.ds.lookahead >= MIN_MATCH) + INSERT_STRING(state.ds.strstart, hash_head); + + /* Find the longest match, discarding those <= prev_length. + */ + state.ds.prev_length = match_length, prev_match = state.ds.match_start; + match_length = MIN_MATCH-1; + + if (hash_head != NIL && state.ds.prev_length < state.ds.max_lazy_match && + state.ds.strstart - hash_head <= MAX_DIST) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + /* Do not look for matches beyond the end of the input. + * This is necessary to make deflate deterministic. + */ + if ((unsigned)state.ds.nice_match > state.ds.lookahead) state.ds.nice_match = (int)state.ds.lookahead; + match_length = longest_match (state,hash_head); + /* longest_match() sets match_start */ + if (match_length > state.ds.lookahead) match_length = state.ds.lookahead; + + /* Ignore a length 3 match if it is too distant: */ + if (match_length == MIN_MATCH && state.ds.strstart-state.ds.match_start > TOO_FAR){ + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (state.ds.prev_length >= MIN_MATCH && match_length <= state.ds.prev_length) { + unsigned max_insert = state.ds.strstart + state.ds.lookahead - MIN_MATCH; + check_match(state,state.ds.strstart-1, prev_match, state.ds.prev_length); + flush = ct_tally(state,state.ds.strstart-1-prev_match, state.ds.prev_length - MIN_MATCH); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. + */ + state.ds.lookahead -= state.ds.prev_length-1; + state.ds.prev_length -= 2; + do { + if (++state.ds.strstart <= max_insert) { + INSERT_STRING(state.ds.strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } + } while (--state.ds.prev_length != 0); + state.ds.strstart++; + match_available = 0; + match_length = MIN_MATCH-1; + + if (flush) FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart; + + } else if (match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + if (ct_tally (state,0, state.ds.window[state.ds.strstart-1])) { + FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart; + } + state.ds.strstart++; + state.ds.lookahead--; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + match_available = 1; + state.ds.strstart++; + state.ds.lookahead--; + } +// Assert(state,strstart <= isize && lookahead <= isize, "a bit too far"); + + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state); + } + if (match_available) ct_tally (state,0, state.ds.window[state.ds.strstart-1]); + + return FLUSH_BLOCK(state,1); /* eof */ +} + + + + + + + + + + + + +int putlocal(struct zlist far *z, WRITEFUNC wfunc,void *param) +{ // Write a local header described by *z to file *f. Return a ZE_ error code. + PUTLG(LOCSIG, f); + PUTSH(z->ver, f); + PUTSH(z->lflg, f); + PUTSH(z->how, f); + PUTLG(z->tim, f); + PUTLG(z->crc, f); + PUTLG(z->siz, f); + PUTLG(z->len, f); + PUTSH(z->nam, f); + PUTSH(z->ext, f); + size_t res = (size_t)wfunc(param, z->iname, (unsigned int)z->nam); + if (res!=z->nam) return ZE_TEMP; + if (z->ext) + { res = (size_t)wfunc(param, z->extra, (unsigned int)z->ext); + if (res!=z->ext) return ZE_TEMP; + } + return ZE_OK; +} + +int putextended(struct zlist far *z, WRITEFUNC wfunc, void *param) +{ // Write an extended local header described by *z to file *f. Returns a ZE_ code + PUTLG(EXTLOCSIG, f); + PUTLG(z->crc, f); + PUTLG(z->siz, f); + PUTLG(z->len, f); + return ZE_OK; +} + +int putcentral(struct zlist far *z, WRITEFUNC wfunc, void *param) +{ // Write a central header entry of *z to file *f. Returns a ZE_ code. + PUTLG(CENSIG, f); + PUTSH(z->vem, f); + PUTSH(z->ver, f); + PUTSH(z->flg, f); + PUTSH(z->how, f); + PUTLG(z->tim, f); + PUTLG(z->crc, f); + PUTLG(z->siz, f); + PUTLG(z->len, f); + PUTSH(z->nam, f); + PUTSH(z->cext, f); + PUTSH(z->com, f); + PUTSH(z->dsk, f); + PUTSH(z->att, f); + PUTLG(z->atx, f); + PUTLG(z->off, f); + if ((size_t)wfunc(param, z->iname, (unsigned int)z->nam) != z->nam || + (z->cext && (size_t)wfunc(param, z->cextra, (unsigned int)z->cext) != z->cext) || + (z->com && (size_t)wfunc(param, z->comment, (unsigned int)z->com) != z->com)) + return ZE_TEMP; + return ZE_OK; +} + + +int putend(int n, ulg s, ulg c, extent m, char *z, WRITEFUNC wfunc, void *param) +{ // write the end of the central-directory-data to file *f. + PUTLG(ENDSIG, f); + PUTSH(0, f); + PUTSH(0, f); + PUTSH(n, f); + PUTSH(n, f); + PUTLG(s, f); + PUTLG(c, f); + PUTSH(m, f); + // Write the comment, if any + if (m && wfunc(param, z, (unsigned int)m) != m) return ZE_TEMP; + return ZE_OK; +} + + + + + + +const ulg crc_table[256] = { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, + 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, + 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, + 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, + 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, + 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, + 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, + 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, + 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, + 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, + 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, + 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, + 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, + 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, + 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, + 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, + 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, + 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, + 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, + 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, + 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, + 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, + 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, + 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, + 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, + 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, + 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, + 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, + 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, + 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, + 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, + 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, + 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, + 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, + 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, + 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, + 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, + 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, + 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, + 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, + 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, + 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, + 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, + 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, + 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, + 0x2d02ef8dL +}; + +#define CRC32(c, b) (crc_table[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8)) +#define DO1(buf) crc = CRC32(crc, *buf++) +#define DO2(buf) DO1(buf); DO1(buf) +#define DO4(buf) DO2(buf); DO2(buf) +#define DO8(buf) DO4(buf); DO4(buf) + +ulg crc32(ulg crc, const uch *buf, extent len) +{ if (buf==NULL) return 0L; + crc = crc ^ 0xffffffffL; + while (len >= 8) {DO8(buf); len -= 8;} + if (len) do {DO1(buf);} while (--len); + return crc ^ 0xffffffffL; // (instead of ~c for 64-bit machines) +} + + +void update_keys(unsigned long *keys, char c) +{ keys[0] = CRC32(keys[0],c); + keys[1] += keys[0] & 0xFF; + keys[1] = keys[1]*134775813L +1; + keys[2] = CRC32(keys[2], keys[1] >> 24); +} +char decrypt_byte(unsigned long *keys) +{ unsigned temp = ((unsigned)keys[2] & 0xffff) | 2; + return (char)(((temp * (temp ^ 1)) >> 8) & 0xff); +} +char zencode(unsigned long *keys, char c) +{ int t=decrypt_byte(keys); + update_keys(keys,c); + return (char)(t^c); +} + + + + + + + +bool HasZipSuffix(const TCHAR *fn) +{ const TCHAR *ext = fn+_tcslen(fn); + while (ext>fn && *ext!='.') ext--; + if (ext==fn && *ext!='.') return false; + if (_tcsicmp(ext,_T(".Z"))==0) return true; + if (_tcsicmp(ext,_T(".zip"))==0) return true; + if (_tcsicmp(ext,_T(".zoo"))==0) return true; + if (_tcsicmp(ext,_T(".arc"))==0) return true; + if (_tcsicmp(ext,_T(".lzh"))==0) return true; + if (_tcsicmp(ext,_T(".arj"))==0) return true; + if (_tcsicmp(ext,_T(".gz"))==0) return true; + if (_tcsicmp(ext,_T(".tgz"))==0) return true; + return false; +} + + +lutime_t filetime2timet(const FILETIME ft) +{ __int64 i = *(__int64*)&ft; + return (lutime_t)((i-116444736000000000)/10000000); +} + +void filetime2dosdatetime(const FILETIME ft, WORD *dosdate,WORD *dostime) +{ // date: bits 0-4 are day of month 1-31. Bits 5-8 are month 1..12. Bits 9-15 are year-1980 + // time: bits 0-4 are seconds/2, bits 5-10 are minute 0..59. Bits 11-15 are hour 0..23 + SYSTEMTIME st; FileTimeToSystemTime(&ft,&st); + *dosdate = (WORD)(((st.wYear-1980)&0x7f) << 9); + *dosdate |= (WORD)((st.wMonth&0xf) << 5); + *dosdate |= (WORD)((st.wDay&0x1f)); + *dostime = (WORD)((st.wHour&0x1f) << 11); + *dostime |= (WORD)((st.wMinute&0x3f) << 5); + *dostime |= (WORD)((st.wSecond*2)&0x1f); +} + + +ZRESULT GetFileInfo(HANDLE hf, ulg *attr, long *size, iztimes *times, ulg *timestamp) +{ // The handle must be a handle to a file + // The date and time is returned in a long with the date most significant to allow + // unsigned integer comparison of absolute times. The attributes have two + // high bytes unix attr, and two low bytes a mapping of that to DOS attr. + //struct stat s; int res=stat(fn,&s); if (res!=0) return false; + // translate windows file attributes into zip ones. + BY_HANDLE_FILE_INFORMATION bhi; BOOL res=GetFileInformationByHandle(hf,&bhi); + if (!res) return ZR_NOFILE; + DWORD fa=bhi.dwFileAttributes; ulg a=0; + // Zip uses the lower word for its interpretation of windows stuff + if (fa&FILE_ATTRIBUTE_READONLY) a|=0x01; + if (fa&FILE_ATTRIBUTE_HIDDEN) a|=0x02; + if (fa&FILE_ATTRIBUTE_SYSTEM) a|=0x04; + if (fa&FILE_ATTRIBUTE_DIRECTORY)a|=0x10; + if (fa&FILE_ATTRIBUTE_ARCHIVE) a|=0x20; + // It uses the upper word for standard unix attr, which we manually construct + if (fa&FILE_ATTRIBUTE_DIRECTORY)a|=0x40000000; // directory + else a|=0x80000000; // normal file + a|=0x01000000; // readable + if (fa&FILE_ATTRIBUTE_READONLY) {} else a|=0x00800000; // writeable + // now just a small heuristic to check if it's an executable: + DWORD red, hsize=GetFileSize(hf,NULL); if (hsize>40) + { SetFilePointer(hf,0,NULL,FILE_BEGIN); unsigned short magic; ReadFile(hf,&magic,sizeof(magic),&red,NULL); + SetFilePointer(hf,36,NULL,FILE_BEGIN); unsigned long hpos; ReadFile(hf,&hpos,sizeof(hpos),&red,NULL); + if (magic==0x54AD && hsize>hpos+4+20+28) + { SetFilePointer(hf,hpos,NULL,FILE_BEGIN); unsigned long signature; ReadFile(hf,&signature,sizeof(signature),&red,NULL); + if (signature==IMAGE_DOS_SIGNATURE || signature==IMAGE_OS2_SIGNATURE + || signature==IMAGE_OS2_SIGNATURE_LE || signature==IMAGE_NT_SIGNATURE) + { a |= 0x00400000; // executable + } + } + } + // + if (attr!=NULL) *attr = a; + if (size!=NULL) *size = hsize; + if (times!=NULL) + { // lutime_t is 32bit number of seconds elapsed since 0:0:0GMT, Jan1, 1970. + // but FILETIME is 64bit number of 100-nanosecs since Jan1, 1601 + times->atime = filetime2timet(bhi.ftLastAccessTime); + times->mtime = filetime2timet(bhi.ftLastWriteTime); + times->ctime = filetime2timet(bhi.ftCreationTime); + } + if (timestamp!=NULL) + { WORD dosdate,dostime; + filetime2dosdatetime(bhi.ftLastWriteTime,&dosdate,&dostime); + *timestamp = (WORD)dostime | (((DWORD)dosdate)<<16); + } + return ZR_OK; +} + + + + + + + + +class TZip +{ public: + TZip(const char *pwd) : hfout(0),mustclosehfout(false),hmapout(0),zfis(0),obuf(0),hfin(0),writ(0),oerr(false),hasputcen(false),ooffset(0),encwriting(false),encbuf(0),password(0), state(0) {if (pwd!=0 && *pwd!=0) {password=new char[strlen(pwd)+1]; strcpy(password,pwd);}} + ~TZip() {if (state!=0) delete state; state=0; if (encbuf!=0) delete[] encbuf; encbuf=0; if (password!=0) delete[] password; password=0;} + + // These variables say about the file we're writing into + // We can write to pipe, file-by-handle, file-by-name, memory-to-memmapfile + char *password; // keep a copy of the password + HANDLE hfout; // if valid, we'll write here (for files or pipes) + bool mustclosehfout; // if true, we are responsible for closing hfout + HANDLE hmapout; // otherwise, we'll write here (for memmap) + unsigned ooffset; // for hfout, this is where the pointer was initially + ZRESULT oerr; // did a write operation give rise to an error? + unsigned writ; // how far have we written. This is maintained by Add, not write(), to avoid confusion over seeks + bool ocanseek; // can we seek? + char *obuf; // this is where we've locked mmap to view. + unsigned int opos; // current pos in the mmap + unsigned int mapsize; // the size of the map we created + bool hasputcen; // have we yet placed the central directory? + bool encwriting; // if true, then we'll encrypt stuff using 'keys' before we write it to disk + unsigned long keys[3]; // keys are initialised inside Add() + char *encbuf; // if encrypting, then this is a temporary workspace for encrypting the data + unsigned int encbufsize; // (to be used and resized inside write(), and deleted in the destructor) + // + TZipFileInfo *zfis; // each file gets added onto this list, for writing the table at the end + TState *state; // we use just one state object per zip, because it's big (500k) + + ZRESULT Create(void *z,unsigned int len,DWORD flags); + static unsigned sflush(void *param,const char *buf, unsigned *size); + static unsigned swrite(void *param,const char *buf, unsigned size); + unsigned int write(const char *buf,unsigned int size); + bool oseek(unsigned int pos); + ZRESULT GetMemory(void **pbuf, unsigned long *plen); + ZRESULT Close(); + + // some variables to do with the file currently being read: + // I haven't done it object-orientedly here, just put them all + // together, since OO didn't seem to make the design any clearer. + ulg attr; iztimes times; ulg timestamp; // all open_* methods set these + bool iseekable; long isize,ired; // size is not set until close() on pips + ulg crc; // crc is not set until close(). iwrit is cumulative + HANDLE hfin; bool selfclosehf; // for input files and pipes + const char *bufin; unsigned int lenin,posin; // for memory + // and a variable for what we've done with the input: (i.e. compressed it!) + ulg csize; // compressed size, set by the compression routines + // and this is used by some of the compression routines + char buf[16384]; + + + ZRESULT open_file(const TCHAR *fn); + ZRESULT open_handle(HANDLE hf,unsigned int len); + ZRESULT open_mem(void *src,unsigned int len); + ZRESULT open_dir(); + static unsigned sread(TState &s,char *buf,unsigned size); + unsigned read(char *buf, unsigned size); + ZRESULT iclose(); + + ZRESULT ideflate(TZipFileInfo *zfi); + ZRESULT istore(); + + ZRESULT Add(const TCHAR *odstzn, void *src,unsigned int len, DWORD flags); + ZRESULT AddCentral(); + +}; + + + +ZRESULT TZip::Create(void *z,unsigned int len,DWORD flags) +{ if (hfout!=0 || hmapout!=0 || obuf!=0 || writ!=0 || oerr!=ZR_OK || hasputcen) return ZR_NOTINITED; + // + if (flags==ZIP_HANDLE) + { HANDLE hf = (HANDLE)z; + hfout=hf; mustclosehfout=false; +#ifdef DuplicateHandle + BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&hfout,0,FALSE,DUPLICATE_SAME_ACCESS); + if (res) mustclosehandle=true; +#endif + // now we have hfout. Either we duplicated the handle and we close it ourselves + // (while the caller closes h themselves), or we couldn't duplicate it. + DWORD res = SetFilePointer(hfout,0,0,FILE_CURRENT); + ocanseek = (res!=0xFFFFFFFF); + if (ocanseek) ooffset=res; else ooffset=0; + return ZR_OK; + } + else if (flags==ZIP_FILENAME) + { const TCHAR *fn = (const TCHAR*)z; + hfout = CreateFile(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); + if (hfout==INVALID_HANDLE_VALUE) {hfout=0; return ZR_NOFILE;} + ocanseek=true; + ooffset=0; + mustclosehfout=true; + return ZR_OK; + } + else if (flags==ZIP_MEMORY) + { unsigned int size = len; + if (size==0) return ZR_MEMSIZE; + if (z!=0) obuf=(char*)z; + else + { hmapout = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,size,NULL); + if (hmapout==NULL) return ZR_NOALLOC; + obuf = (char*)MapViewOfFile(hmapout,FILE_MAP_ALL_ACCESS,0,0,size); + if (obuf==0) {CloseHandle(hmapout); hmapout=0; return ZR_NOALLOC;} + } + ocanseek=true; + opos=0; mapsize=size; + return ZR_OK; + } + else return ZR_ARGS; +} + +unsigned TZip::sflush(void *param,const char *buf, unsigned *size) +{ // static + if (*size==0) return 0; + TZip *zip = (TZip*)param; + unsigned int writ = zip->write(buf,*size); + if (writ!=0) *size=0; + return writ; +} +unsigned TZip::swrite(void *param,const char *buf, unsigned size) +{ // static + if (size==0) return 0; + TZip *zip=(TZip*)param; return zip->write(buf,size); +} +unsigned int TZip::write(const char *buf,unsigned int size) +{ const char *srcbuf=buf; + if (encwriting) + { if (encbuf!=0 && encbufsize=mapsize) {oerr=ZR_MEMSIZE; return 0;} + memcpy(obuf+opos, srcbuf, size); + opos+=size; + return size; + } + else if (hfout!=0) + { DWORD writ; WriteFile(hfout,srcbuf,size,&writ,NULL); + return writ; + } + oerr=ZR_NOTINITED; return 0; +} + +bool TZip::oseek(unsigned int pos) +{ if (!ocanseek) {oerr=ZR_SEEK; return false;} + if (obuf!=0) + { if (pos>=mapsize) {oerr=ZR_MEMSIZE; return false;} + opos=pos; + return true; + } + else if (hfout!=0) + { SetFilePointer(hfout,pos+ooffset,NULL,FILE_BEGIN); + return true; + } + oerr=ZR_NOTINITED; return 0; +} + +ZRESULT TZip::GetMemory(void **pbuf, unsigned long *plen) +{ // When the user calls GetMemory, they're presumably at the end + // of all their adding. In any case, we have to add the central + // directory now, otherwise the memory we tell them won't be complete. + if (!hasputcen) AddCentral(); hasputcen=true; + if (pbuf!=NULL) *pbuf=(void*)obuf; + if (plen!=NULL) *plen=writ; + if (obuf==NULL) return ZR_NOTMMAP; + return ZR_OK; +} + +ZRESULT TZip::Close() +{ // if the directory hadn't already been added through a call to GetMemory, + // then we do it now + ZRESULT res=ZR_OK; if (!hasputcen) res=AddCentral(); hasputcen=true; + if (obuf!=0 && hmapout!=0) UnmapViewOfFile(obuf); obuf=0; + if (hmapout!=0) CloseHandle(hmapout); hmapout=0; + if (hfout!=0 && mustclosehfout) CloseHandle(hfout); hfout=0; mustclosehfout=false; + return res; +} + + + + +ZRESULT TZip::open_file(const TCHAR *fn) +{ hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0; + if (fn==0) return ZR_ARGS; + HANDLE hf = CreateFile(fn,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); + if (hf==INVALID_HANDLE_VALUE) return ZR_NOFILE; + ZRESULT res = open_handle(hf,0); + if (res!=ZR_OK) {CloseHandle(hf); return res;} + selfclosehf=true; + return ZR_OK; +} +ZRESULT TZip::open_handle(HANDLE hf,unsigned int len) +{ hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0; + if (hf==0 || hf==INVALID_HANDLE_VALUE) return ZR_ARGS; + DWORD res = SetFilePointer(hfout,0,0,FILE_CURRENT); + if (res!=0xFFFFFFFF) + { ZRESULT res = GetFileInfo(hf,&attr,&isize,×,×tamp); + if (res!=ZR_OK) return res; + SetFilePointer(hf,0,NULL,FILE_BEGIN); // because GetFileInfo will have screwed it up + iseekable=true; hfin=hf; + return ZR_OK; + } + else + { attr= 0x80000000; // just a normal file + isize = -1; // can't know size until at the end + if (len!=0) isize=len; // unless we were told explicitly! + iseekable=false; + SYSTEMTIME st; GetLocalTime(&st); + FILETIME ft; SystemTimeToFileTime(&st,&ft); + WORD dosdate,dostime; filetime2dosdatetime(ft,&dosdate,&dostime); + times.atime = filetime2timet(ft); + times.mtime = times.atime; + times.ctime = times.atime; + timestamp = (WORD)dostime | (((DWORD)dosdate)<<16); + hfin=hf; + return ZR_OK; + } +} +ZRESULT TZip::open_mem(void *src,unsigned int len) +{ hfin=0; bufin=(const char*)src; selfclosehf=false; crc=CRCVAL_INITIAL; ired=0; csize=0; ired=0; + lenin=len; posin=0; + if (src==0 || len==0) return ZR_ARGS; + attr= 0x80000000; // just a normal file + isize = len; + iseekable=true; + SYSTEMTIME st; GetLocalTime(&st); + FILETIME ft; SystemTimeToFileTime(&st,&ft); + WORD dosdate,dostime; filetime2dosdatetime(ft,&dosdate,&dostime); + times.atime = filetime2timet(ft); + times.mtime = times.atime; + times.ctime = times.atime; + timestamp = (WORD)dostime | (((DWORD)dosdate)<<16); + return ZR_OK; +} +ZRESULT TZip::open_dir() +{ hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0; + attr= 0x41C00010; // a readable writable directory, and again directory + isize = 0; + iseekable=false; + SYSTEMTIME st; GetLocalTime(&st); + FILETIME ft; SystemTimeToFileTime(&st,&ft); + WORD dosdate,dostime; filetime2dosdatetime(ft,&dosdate,&dostime); + times.atime = filetime2timet(ft); + times.mtime = times.atime; + times.ctime = times.atime; + timestamp = (WORD)dostime | (((DWORD)dosdate)<<16); + return ZR_OK; +} + +unsigned TZip::sread(TState &s,char *buf,unsigned size) +{ // static + TZip *zip = (TZip*)s.param; + return zip->read(buf,size); +} + +unsigned TZip::read(char *buf, unsigned size) +{ if (bufin!=0) + { if (posin>=lenin) return 0; // end of input + ulg red = lenin-posin; + if (red>size) red=size; + memcpy(buf, bufin+posin, red); + posin += red; + ired += red; + crc = crc32(crc, (uch*)buf, red); + return red; + } + else if (hfin!=0) + { DWORD red; + BOOL ok = ReadFile(hfin,buf,size,&red,NULL); + if (!ok) return 0; + ired += red; + crc = crc32(crc, (uch*)buf, red); + return red; + } + else {oerr=ZR_NOTINITED; return 0;} +} + +ZRESULT TZip::iclose() +{ if (selfclosehf && hfin!=0) CloseHandle(hfin); hfin=0; + bool mismatch = (isize!=-1 && isize!=ired); + isize=ired; // and crc has been being updated anyway + if (mismatch) return ZR_MISSIZE; + else return ZR_OK; +} + + + +ZRESULT TZip::ideflate(TZipFileInfo *zfi) +{ if (state==0) state=new TState(); + // It's a very big object! 500k! We allocate it on the heap, because PocketPC's + // stack breaks if we try to put it all on the stack. It will be deleted lazily + state->err=0; + state->readfunc=sread; state->flush_outbuf=sflush; + state->param=this; state->level=8; state->seekable=iseekable; state->err=NULL; + // the following line will make ct_init realise it has to perform the init + state->ts.static_dtree[0].dl.len = 0; + // Thanks to Alvin77 for this crucial fix: + state->ds.window_size=0; + // I think that covers everything that needs to be initted. + // + bi_init(*state,buf, sizeof(buf), TRUE); // it used to be just 1024-size, not 16384 as here + ct_init(*state,&zfi->att); + lm_init(*state,state->level, &zfi->flg); + ulg sz = deflate(*state); + csize=sz; + ZRESULT r=ZR_OK; if (state->err!=NULL) r=ZR_FLATE; + return r; +} + +ZRESULT TZip::istore() +{ ulg size=0; + for (;;) + { unsigned int cin=read(buf,16384); if (cin<=0 || cin==(unsigned int)EOF) break; + unsigned int cout = write(buf,cin); if (cout!=cin) return ZR_MISSIZE; + size += cin; + } + csize=size; + return ZR_OK; +} + + + + + +bool has_seeded=false; +ZRESULT TZip::Add(const TCHAR *odstzn, void *src,unsigned int len, DWORD flags) +{ if (oerr) return ZR_FAILED; + if (hasputcen) return ZR_ENDED; + + // if we use password encryption, then every isize and csize is 12 bytes bigger + int passex=0; if (password!=0 && flags!=ZIP_FOLDER) passex=12; + + // zip has its own notion of what its names should look like: i.e. dir/file.stuff + TCHAR dstzn[MAX_PATH]; _tcscpy(dstzn,odstzn); + if (*dstzn==0) return ZR_ARGS; + TCHAR *d=dstzn; while (*d!=0) {if (*d=='\\') *d='/'; d++;} + bool isdir = (flags==ZIP_FOLDER); + bool needs_trailing_slash = (isdir && dstzn[_tcslen(dstzn)-1]!='/'); + int method=DEFLATE; if (isdir || HasZipSuffix(dstzn)) method=STORE; + + // now open whatever was our input source: + ZRESULT openres; + if (flags==ZIP_FILENAME) openres=open_file((const TCHAR*)src); + else if (flags==ZIP_HANDLE) openres=open_handle((HANDLE)src,len); + else if (flags==ZIP_MEMORY) openres=open_mem(src,len); + else if (flags==ZIP_FOLDER) openres=open_dir(); + else return ZR_ARGS; + if (openres!=ZR_OK) return openres; + + // A zip "entry" consists of a local header (which includes the file name), + // then the compressed data, and possibly an extended local header. + + // Initialize the local header + TZipFileInfo zfi; zfi.nxt=NULL; + strcpy(zfi.name,""); +#ifdef UNICODE + WideCharToMultiByte(CP_UTF8,0,dstzn,-1,zfi.iname,MAX_PATH,0,0); +#else + strcpy(zfi.iname,dstzn); +#endif + zfi.nam=strlen(zfi.iname); + if (needs_trailing_slash) {strcat(zfi.iname,"/"); zfi.nam++;} + strcpy(zfi.zname,""); + zfi.extra=NULL; zfi.ext=0; // extra header to go after this compressed data, and its length + zfi.cextra=NULL; zfi.cext=0; // extra header to go in the central end-of-zip directory, and its length + zfi.comment=NULL; zfi.com=0; // comment, and its length + zfi.mark = 1; + zfi.dosflag = 0; + zfi.att = (ush)BINARY; + zfi.vem = (ush)0xB17; // 0xB00 is win32 os-code. 0x17 is 23 in decimal: zip 2.3 + zfi.ver = (ush)20; // Needs PKUNZIP 2.0 to unzip it + zfi.tim = timestamp; + // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc. + zfi.crc = 0; // to be updated later + zfi.flg = 8; // 8 means 'there is an extra header'. Assume for the moment that we need it. + if (password!=0 && !isdir) zfi.flg=9; // and 1 means 'password-encrypted' + zfi.lflg = zfi.flg; // to be updated later + zfi.how = (ush)method; // to be updated later + zfi.siz = (ulg)(method==STORE && isize>=0 ? isize+passex : 0); // to be updated later + zfi.len = (ulg)(isize); // to be updated later + zfi.dsk = 0; + zfi.atx = attr; + zfi.off = writ+ooffset; // offset within file of the start of this local record + // stuff the 'times' structure into zfi.extra + + // nb. apparently there's a problem with PocketPC CE(zip)->CE(unzip) fails. And removing the following block fixes it up. + char xloc[EB_L_UT_SIZE]; zfi.extra=xloc; zfi.ext=EB_L_UT_SIZE; + char xcen[EB_C_UT_SIZE]; zfi.cextra=xcen; zfi.cext=EB_C_UT_SIZE; + xloc[0] = 'U'; + xloc[1] = 'T'; + xloc[2] = EB_UT_LEN(3); // length of data part of e.f. + xloc[3] = 0; + xloc[4] = EB_UT_FL_MTIME | EB_UT_FL_ATIME | EB_UT_FL_CTIME; + xloc[5] = (char)(times.mtime); + xloc[6] = (char)(times.mtime >> 8); + xloc[7] = (char)(times.mtime >> 16); + xloc[8] = (char)(times.mtime >> 24); + xloc[9] = (char)(times.atime); + xloc[10] = (char)(times.atime >> 8); + xloc[11] = (char)(times.atime >> 16); + xloc[12] = (char)(times.atime >> 24); + xloc[13] = (char)(times.ctime); + xloc[14] = (char)(times.ctime >> 8); + xloc[15] = (char)(times.ctime >> 16); + xloc[16] = (char)(times.ctime >> 24); + memcpy(zfi.cextra,zfi.extra,EB_C_UT_SIZE); + zfi.cextra[EB_LEN] = EB_UT_LEN(1); + + + // (1) Start by writing the local header: + int r = putlocal(&zfi,swrite,this); + if (r!=ZE_OK) {iclose(); return ZR_WRITE;} + writ += 4 + LOCHEAD + (unsigned int)zfi.nam + (unsigned int)zfi.ext; + if (oerr!=ZR_OK) {iclose(); return oerr;} + + // (1.5) if necessary, write the encryption header + keys[0]=305419896L; + keys[1]=591751049L; + keys[2]=878082192L; + for (const char *cp=password; cp!=0 && *cp!=0; cp++) update_keys(keys,*cp); + // generate some random bytes + if (!has_seeded) srand(GetTickCount()^(unsigned long)GetDesktopWindow()); + char encbuf[12]; for (int i=0; i<12; i++) encbuf[i]=(char)((rand()>>7)&0xff); + encbuf[11] = (char)((zfi.tim>>8)&0xff); + for (int ei=0; ei<12; ei++) encbuf[ei]=zencode(keys,encbuf[ei]); + if (password!=0 && !isdir) {swrite(this,encbuf,12); writ+=12;} + + //(2) Write deflated/stored file to zip file + ZRESULT writeres=ZR_OK; + encwriting = (password!=0 && !isdir); // an object member variable to say whether we write to disk encrypted + if (!isdir && method==DEFLATE) writeres=ideflate(&zfi); + else if (!isdir && method==STORE) writeres=istore(); + else if (isdir) csize=0; + encwriting = false; + iclose(); + writ += csize; + if (oerr!=ZR_OK) return oerr; + if (writeres!=ZR_OK) return ZR_WRITE; + + // (3) Either rewrite the local header with correct information... + bool first_header_has_size_right = (zfi.siz==csize+passex); + zfi.crc = crc; + zfi.siz = csize+passex; + zfi.len = isize; + if (ocanseek && (password==0 || isdir)) + { zfi.how = (ush)method; + if ((zfi.flg & 1) == 0) zfi.flg &= ~8; // clear the extended local header flag + zfi.lflg = zfi.flg; + // rewrite the local header: + if (!oseek(zfi.off-ooffset)) return ZR_SEEK; + if ((r = putlocal(&zfi, swrite,this)) != ZE_OK) return ZR_WRITE; + if (!oseek(writ)) return ZR_SEEK; + } + else + { // (4) ... or put an updated header at the end + if (zfi.how != (ush) method) return ZR_NOCHANGE; + if (method==STORE && !first_header_has_size_right) return ZR_NOCHANGE; + if ((r = putextended(&zfi, swrite,this)) != ZE_OK) return ZR_WRITE; + writ += 16L; + zfi.flg = zfi.lflg; // if flg modified by inflate, for the central index + } + if (oerr!=ZR_OK) return oerr; + + // Keep a copy of the zipfileinfo, for our end-of-zip directory + char *cextra = new char[zfi.cext]; memcpy(cextra,zfi.cextra,zfi.cext); zfi.cextra=cextra; + TZipFileInfo *pzfi = new TZipFileInfo; memcpy(pzfi,&zfi,sizeof(zfi)); + if (zfis==NULL) zfis=pzfi; + else {TZipFileInfo *z=zfis; while (z->nxt!=NULL) z=z->nxt; z->nxt=pzfi;} + return ZR_OK; +} + +ZRESULT TZip::AddCentral() +{ // write central directory + int numentries = 0; + ulg pos_at_start_of_central = writ; + //ulg tot_unc_size=0, tot_compressed_size=0; + bool okay=true; + for (TZipFileInfo *zfi=zfis; zfi!=NULL; ) + { if (okay) + { int res = putcentral(zfi, swrite,this); + if (res!=ZE_OK) okay=false; + } + writ += 4 + CENHEAD + (unsigned int)zfi->nam + (unsigned int)zfi->cext + (unsigned int)zfi->com; + //tot_unc_size += zfi->len; + //tot_compressed_size += zfi->siz; + numentries++; + // + TZipFileInfo *zfinext = zfi->nxt; + if (zfi->cextra!=0) delete[] zfi->cextra; + delete zfi; + zfi = zfinext; + } + ulg center_size = writ - pos_at_start_of_central; + if (okay) + { int res = putend(numentries, center_size, pos_at_start_of_central+ooffset, 0, NULL, swrite,this); + if (res!=ZE_OK) okay=false; + writ += 4 + ENDHEAD + 0; + } + if (!okay) return ZR_WRITE; + return ZR_OK; +} + + + + + +ZRESULT lasterrorZ=ZR_OK; + +unsigned int FormatZipMessageZ(ZRESULT code, char *buf,unsigned int len) +{ if (code==ZR_RECENT) code=lasterrorZ; + const char *msg="unknown zip result code"; + switch (code) + { case ZR_OK: msg="Success"; break; + case ZR_NODUPH: msg="Culdn't duplicate handle"; break; + case ZR_NOFILE: msg="Couldn't create/open file"; break; + case ZR_NOALLOC: msg="Failed to allocate memory"; break; + case ZR_WRITE: msg="Error writing to file"; break; + case ZR_NOTFOUND: msg="File not found in the zipfile"; break; + case ZR_MORE: msg="Still more data to unzip"; break; + case ZR_CORRUPT: msg="Zipfile is corrupt or not a zipfile"; break; + case ZR_READ: msg="Error reading file"; break; + case ZR_ARGS: msg="Caller: faulty arguments"; break; + case ZR_PARTIALUNZ: msg="Caller: the file had already been partially unzipped"; break; + case ZR_NOTMMAP: msg="Caller: can only get memory of a memory zipfile"; break; + case ZR_MEMSIZE: msg="Caller: not enough space allocated for memory zipfile"; break; + case ZR_FAILED: msg="Caller: there was a previous error"; break; + case ZR_ENDED: msg="Caller: additions to the zip have already been ended"; break; + case ZR_ZMODE: msg="Caller: mixing creation and opening of zip"; break; + case ZR_NOTINITED: msg="Zip-bug: internal initialisation not completed"; break; + case ZR_SEEK: msg="Zip-bug: trying to seek the unseekable"; break; + case ZR_MISSIZE: msg="Zip-bug: the anticipated size turned out wrong"; break; + case ZR_NOCHANGE: msg="Zip-bug: tried to change mind, but not allowed"; break; + case ZR_FLATE: msg="Zip-bug: an internal error during flation"; break; + } + unsigned int mlen=(unsigned int)strlen(msg); + if (buf==0 || len==0) return mlen; + unsigned int n=mlen; if (n+1>len) n=len-1; + strncpy(buf,msg,n); buf[n]=0; + return mlen; +} + + + +typedef struct +{ DWORD flag; + TZip *zip; +} TZipHandleData; + + +HZIP CreateZipInternal(void *z,unsigned int len,DWORD flags, const char *password) +{ TZip *zip = new TZip(password); + lasterrorZ = zip->Create(z,len,flags); + if (lasterrorZ!=ZR_OK) {delete zip; return 0;} + TZipHandleData *han = new TZipHandleData; + han->flag=2; han->zip=zip; return (HZIP)han; +} +HZIP CreateZipHandle(HANDLE h, const char *password) {return CreateZipInternal(h,0,ZIP_HANDLE,password);} +HZIP CreateZip(const TCHAR *fn, const char *password) {return CreateZipInternal((void*)fn,0,ZIP_FILENAME,password);} +HZIP CreateZip(void *z,unsigned int len, const char *password) {return CreateZipInternal(z,len,ZIP_MEMORY,password);} + + +ZRESULT ZipAddInternal(HZIP hz,const TCHAR *dstzn, void *src,unsigned int len, DWORD flags) +{ if (hz==0) {lasterrorZ=ZR_ARGS;return ZR_ARGS;} + TZipHandleData *han = (TZipHandleData*)hz; + if (han->flag!=2) {lasterrorZ=ZR_ZMODE;return ZR_ZMODE;} + TZip *zip = han->zip; + lasterrorZ = zip->Add(dstzn,src,len,flags); + return lasterrorZ; +} +ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, const TCHAR *fn) {return ZipAddInternal(hz,dstzn,(void*)fn,0,ZIP_FILENAME);} +ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, void *src,unsigned int len) {return ZipAddInternal(hz,dstzn,src,len,ZIP_MEMORY);} +ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h) {return ZipAddInternal(hz,dstzn,h,0,ZIP_HANDLE);} +ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h, unsigned int len) {return ZipAddInternal(hz,dstzn,h,len,ZIP_HANDLE);} +ZRESULT ZipAddFolder(HZIP hz,const TCHAR *dstzn) {return ZipAddInternal(hz,dstzn,0,0,ZIP_FOLDER);} + + + +ZRESULT ZipGetMemory(HZIP hz, void **buf, unsigned long *len) +{ if (hz==0) {if (buf!=0) *buf=0; if (len!=0) *len=0; lasterrorZ=ZR_ARGS;return ZR_ARGS;} + TZipHandleData *han = (TZipHandleData*)hz; + if (han->flag!=2) {lasterrorZ=ZR_ZMODE;return ZR_ZMODE;} + TZip *zip = han->zip; + lasterrorZ = zip->GetMemory(buf,len); + return lasterrorZ; +} + +ZRESULT CloseZipZ(HZIP hz) +{ if (hz==0) {lasterrorZ=ZR_ARGS;return ZR_ARGS;} + TZipHandleData *han = (TZipHandleData*)hz; + if (han->flag!=2) {lasterrorZ=ZR_ZMODE;return ZR_ZMODE;} + TZip *zip = han->zip; + lasterrorZ = zip->Close(); + delete zip; + delete han; + return lasterrorZ; +} + +bool IsZipHandleZ(HZIP hz) +{ if (hz==0) return false; + TZipHandleData *han = (TZipHandleData*)hz; + return (han->flag==2); +} + diff --git a/uMod2/uMod_GUI/zip.h b/uMod2/uMod_GUI/zip.h new file mode 100644 index 0000000..a3480a1 --- /dev/null +++ b/uMod2/uMod_GUI/zip.h @@ -0,0 +1,203 @@ +#ifndef _zip_H +#define _zip_H + + +// ZIP functions -- for creating zip files +// This file is a repackaged form of the Info-Zip source code available +// at www.info-zip.org. The original copyright notice may be found in +// zip.cpp. The repackaging was done by Lucian Wischik to simplify and +// extend its use in Windows/C++. Also to add encryption and unicode. + + +#ifndef _unzip_H +DECLARE_HANDLE(HZIP); +#endif +// An HZIP identifies a zip file that is being created + +typedef DWORD ZRESULT; +// return codes from any of the zip functions. Listed later. + + + +HZIP CreateZip(const TCHAR *fn, const char *password); +HZIP CreateZip(void *buf,unsigned int len, const char *password); +HZIP CreateZipHandle(HANDLE h, const char *password); +// CreateZip - call this to start the creation of a zip file. +// As the zip is being created, it will be stored somewhere: +// to a pipe: CreateZipHandle(hpipe_write); +// in a file (by handle): CreateZipHandle(hfile); +// in a file (by name): CreateZip("c:\\test.zip"); +// in memory: CreateZip(buf, len); +// or in pagefile memory: CreateZip(0, len); +// The final case stores it in memory backed by the system paging file, +// where the zip may not exceed len bytes. This is a bit friendlier than +// allocating memory with new[]: it won't lead to fragmentation, and the +// memory won't be touched unless needed. That means you can give very +// large estimates of the maximum-size without too much worry. +// As for the password, it lets you encrypt every file in the archive. +// (This api doesn't support per-file encryption.) +// Note: because pipes don't allow random access, the structure of a zipfile +// created into a pipe is slightly different from that created into a file +// or memory. In particular, the compressed-size of the item cannot be +// stored in the zipfile until after the item itself. (Also, for an item added +// itself via a pipe, the uncompressed-size might not either be known until +// after.) This is not normally a problem. But if you try to unzip via a pipe +// as well, then the unzipper will not know these things about the item until +// after it has been unzipped. Therefore: for unzippers which don't just write +// each item to disk or to a pipe, but instead pre-allocate memory space into +// which to unzip them, then either you have to create the zip not to a pipe, +// or you have to add items not from a pipe, or at least when adding items +// from a pipe you have to specify the length. +// Note: for windows-ce, you cannot close the handle until after CloseZip. +// but for real windows, the zip makes its own copy of your handle, so you +// can close yours anytime. + + +ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, const TCHAR *fn); +ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, void *src,unsigned int len); +ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h); +ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h, unsigned int len); +ZRESULT ZipAddFolder(HZIP hz,const TCHAR *dstzn); +// ZipAdd - call this for each file to be added to the zip. +// dstzn is the name that the file will be stored as in the zip file. +// The file to be added to the zip can come +// from a pipe: ZipAddHandle(hz,"file.dat", hpipe_read); +// from a file: ZipAddHandle(hz,"file.dat", hfile); +// from a filen: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat"); +// from memory: ZipAdd(hz,"subdir\\file.dat", buf,len); +// (folder): ZipAddFolder(hz,"subdir"); +// Note: if adding an item from a pipe, and if also creating the zip file itself +// to a pipe, then you might wish to pass a non-zero length to the ZipAddHandle +// function. This will let the zipfile store the item's size ahead of the +// compressed item itself, which in turn makes it easier when unzipping the +// zipfile from a pipe. + +ZRESULT ZipGetMemory(HZIP hz, void **buf, unsigned long *len); +// ZipGetMemory - If the zip was created in memory, via ZipCreate(0,len), +// then this function will return information about that memory block. +// buf will receive a pointer to its start, and len its length. +// Note: you can't add any more after calling this. + +ZRESULT CloseZip(HZIP hz); +// CloseZip - the zip handle must be closed with this function. + +unsigned int FormatZipMessage(ZRESULT code, TCHAR *buf,unsigned int len); +// FormatZipMessage - given an error code, formats it as a string. +// It returns the length of the error message. If buf/len points +// to a real buffer, then it also writes as much as possible into there. + + + +// These are the result codes: +#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned, +#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage. +// The following come from general system stuff (e.g. files not openable) +#define ZR_GENMASK 0x0000FF00 +#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle +#define ZR_NOFILE 0x00000200 // couldn't create/open the file +#define ZR_NOALLOC 0x00000300 // failed to allocate some resource +#define ZR_WRITE 0x00000400 // a general error writing to the file +#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip +#define ZR_MORE 0x00000600 // there's still more data to be unzipped +#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile +#define ZR_READ 0x00000800 // a general error reading the file +// The following come from mistakes on the part of the caller +#define ZR_CALLERMASK 0x00FF0000 +#define ZR_ARGS 0x00010000 // general mistake with the arguments +#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't +#define ZR_MEMSIZE 0x00030000 // the memory size is too small +#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function +#define ZR_ENDED 0x00050000 // the zip creation has already been closed +#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken +#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped +#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip +// The following come from bugs within the zip library itself +#define ZR_BUGMASK 0xFF000000 +#define ZR_NOTINITED 0x01000000 // initialisation didn't work +#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file +#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed +#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code + + + + + + +// e.g. +// +// (1) Traditional use, creating a zipfile from existing files +// HZIP hz = CreateZip("c:\\simple1.zip",0); +// ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp"); +// ZipAdd(hz,"znsimple.txt", "c:\\simple.txt"); +// CloseZip(hz); +// +// (2) Memory use, creating an auto-allocated mem-based zip file from various sources +// HZIP hz = CreateZip(0,100000, 0); +// // adding a conventional file... +// ZipAdd(hz,"src1.txt", "c:\\src1.txt"); +// // adding something from memory... +// char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F); +// ZipAdd(hz,"file.dat", buf,1000); +// // adding something from a pipe... +// HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0); +// HANDLE hthread = CreateThread(0,0,ThreadFunc,(void*)hwrite,0,0); +// ZipAdd(hz,"unz3.dat", hread,1000); // the '1000' is optional. +// WaitForSingleObject(hthread,INFINITE); +// CloseHandle(hthread); CloseHandle(hread); +// ... meanwhile DWORD WINAPI ThreadFunc(void *dat) +// { HANDLE hwrite = (HANDLE)dat; +// char buf[1000]={17}; +// DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL); +// CloseHandle(hwrite); +// return 0; +// } +// // and now that the zip is created, let's do something with it: +// void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen); +// HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); +// DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL); +// CloseHandle(hfz); +// CloseZip(hz); +// +// (3) Handle use, for file handles and pipes +// HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite,0,0); +// HANDLE hthread = CreateThread(0,0,ZipReceiverThread,(void*)hzread,0,0); +// HZIP hz = CreateZipHandle(hzwrite,0); +// // ... add to it +// CloseZip(hz); +// CloseHandle(hzwrite); +// WaitForSingleObject(hthread,INFINITE); +// CloseHandle(hthread); +// ... meanwhile DWORD WINAPI ZipReceiverThread(void *dat) +// { HANDLE hread = (HANDLE)dat; +// char buf[1000]; +// while (true) +// { DWORD red; ReadFile(hread,buf,1000,&red,NULL); +// // ... and do something with this zip data we're receiving +// if (red==0) break; +// } +// CloseHandle(hread); +// return 0; +// } + + + +// Now we indulge in a little skullduggery so that the code works whether +// the user has included just zip or both zip and unzip. +// Idea: if header files for both zip and unzip are present, then presumably +// the cpp files for zip and unzip are both present, so we will call +// one or the other of them based on a dynamic choice. If the header file +// for only one is present, then we will bind to that particular one. +ZRESULT CloseZipZ(HZIP hz); +unsigned int FormatZipMessageZ(ZRESULT code, char *buf,unsigned int len); +bool IsZipHandleZ(HZIP hz); +#ifdef _unzip_H +#undef CloseZip +#define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz)) +#else +#define CloseZip CloseZipZ +#define FormatZipMessage FormatZipMessageZ +#endif + + + +#endif diff --git a/uMod2/uMod_GlobalDefines.h b/uMod2/uMod_GlobalDefines.h new file mode 100644 index 0000000..00e72fb --- /dev/null +++ b/uMod2/uMod_GlobalDefines.h @@ -0,0 +1,71 @@ +/* +This file is part of Universal Modding Engine. + + +Universal Modding Engine is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Universal Modding Engine is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Universal Modding Engine. If not, see . +*/ + +#ifndef uMod_GlobalDefines_H_ +#define uMod_GlobalDefines_H_ + +//#define MyTypeHash DWORD64 +#define MyTypeHash DWORD32 + +#define BIG_BUFSIZE 1<<24 +#define SMALL_BUFSIZE 1<<10 + +typedef struct +{ + unsigned int Control; + unsigned int Value; + MyTypeHash Hash; +} MsgStruct; + +typedef struct +{ + HANDLE In; + HANDLE Out; +} PipeStruct; + + +#define uMod_APP_DX9 L"uMod_DX9.txt" +#define uMod_APP_DIR L"uMod" +#define uMod_VERSION L"uMod V 1.0" + +#define PIPE_uMod2Game L"\\\\.\\pipe\\uMod2Game" +#define PIPE_Game2uMod L"\\\\.\\pipe\\Game2uMod" + +#define CONTROL_ADD_TEXTURE 1 +#define CONTROL_FORCE_RELOAD_TEXTURE 2 +#define CONTROL_REMOVE_TEXTURE 3 +#define CONTROL_FORCE_RELOAD_TEXTURE_DATA 4 +#define CONTROL_ADD_TEXTURE_DATA 5 +#define CONTROL_MORE_TEXTURES 6 + + +#define CONTROL_SAVE_ALL 10 +#define CONTROL_SAVE_SINGLE 11 +#define CONTROL_SET_DIR 12 + +#define CONTROL_KEY_BACK 20 +#define CONTROL_KEY_SAVE 21 +#define CONTROL_KEY_NEXT 22 + +#define CONTROL_FONT_COLOUR 30 +#define CONTROL_TEXTURE_COLOUR 31 + + + + +#endif